Skip to content

Commit 025d380

Browse files
committed
solve problem
1 parent 8b9bad6 commit 025d380

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
// Time O(k)
3+
// Space O(height of Tree)
4+
func kthSmallest(_ root: TreeNode?, _ k: Int) -> Int {
5+
var count = 0
6+
var result = root!.val
7+
8+
inorderTree(root, &count, k, &result)
9+
10+
return result
11+
}
12+
13+
private func inorderTree(_ node: TreeNode?, _ count: inout Int, _ k: Int, _ result: inout Int) {
14+
guard let node = node else { return }
15+
if count == k { return }
16+
17+
// left search
18+
inorderTree(node.left, &count, k, &result)
19+
20+
// current node
21+
count += 1
22+
if count == k {
23+
result = node.val
24+
return
25+
}
26+
27+
// right search
28+
inorderTree(node.right, &count, k, &result)
29+
}
30+
}
31+

0 commit comments

Comments
 (0)