Skip to content

Commit 1505e9e

Browse files
committed
kth samllest element in a bst
1 parent a7d88ab commit 1505e9e

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
// TC : O(H+K)
3+
// SC: O(H)
4+
private var K: Int = 0
5+
fun kthSmallest(root: TreeNode?, k: Int): Int {
6+
K = k
7+
return traverse(root)!!.`val`
8+
}
9+
10+
fun traverse(cur: TreeNode?): TreeNode?{
11+
if(cur == null) return cur
12+
13+
val result = traverse(cur.left)
14+
K--
15+
if(K == 0) return cur
16+
return result ?: traverse(cur.right)
17+
}
18+
}

0 commit comments

Comments
 (0)