Skip to content

Commit d8898be

Browse files
committed
solve: kth smallest element in a bst
1 parent 0e6833c commit d8898be

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// TC: O(N)
2+
// SC: O(N)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* function TreeNode(val, left, right) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.left = (left===undefined ? null : left)
9+
* this.right = (right===undefined ? null : right)
10+
* }
11+
*/
12+
/**
13+
* @param {TreeNode} root
14+
* @param {number} k
15+
* @return {number}
16+
*/
17+
var kthSmallest = function (root, k) {
18+
let result = null;
19+
20+
dfs(root);
21+
22+
return result;
23+
24+
function dfs(current) {
25+
if (result !== null) {
26+
return;
27+
}
28+
if (!current) {
29+
return;
30+
}
31+
32+
dfs(current.left);
33+
if (current.val >= 0) {
34+
if (k === 1) {
35+
result = current.val;
36+
}
37+
k -= 1;
38+
}
39+
dfs(current.right);
40+
}
41+
};

0 commit comments

Comments
 (0)