Skip to content

Commit 5d0c37b

Browse files
committed
feat: Add solution For LeetCode problem 230
1 parent ab551a4 commit 5d0c37b

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//
2+
// 230. Kth Smallest Element in a BST
3+
// https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/
4+
// Dale-Study
5+
//
6+
// Created by WhiteHyun on 2024/06/27.
7+
//
8+
9+
/**
10+
* Definition for a binary tree node.
11+
* public class TreeNode {
12+
* public var val: Int
13+
* public var left: TreeNode?
14+
* public var right: TreeNode?
15+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
16+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
17+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
18+
* self.val = val
19+
* self.left = left
20+
* self.right = right
21+
* }
22+
* }
23+
*/
24+
class Solution {
25+
private var triedCount: Int = 0
26+
func kthSmallest(_ node: TreeNode?, _ k: Int) -> Int {
27+
guard let node else { return -1 }
28+
let number = kthSmallest(node.left, k)
29+
if number != -1 { return number }
30+
if triedCount + 1 == k { return node.val }
31+
triedCount += 1
32+
return kthSmallest(node.right, k)
33+
}
34+
}

0 commit comments

Comments
 (0)