forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
230-Kth-Smallest-Element-in-a-BST.js
49 lines (39 loc) · 1.07 KB
/
230-Kth-Smallest-Element-in-a-BST.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* https://leetcode.com/problems/kth-smallest-element-in-a-bst/
* Time O(N + K) | Space O(H)
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function(root, k, inOrder = []) {
if (!root) return inOrder
return dfs(root, k, inOrder);
};
const dfs = (root, k, inOrder) => {
if (root.left) kthSmallest(root.left, k, inOrder);
inOrder.push(root.val);
if (root.right) kthSmallest(root.right, k, inOrder);
return inOrder[(k - 1)];
}
/**
* https://leetcode.com/problems/kth-smallest-element-in-a-bst/
* Time O(N + K) | Space O(H)
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function(root, k, stack = []) {
while (k--) {
root = moveLeft(root, stack);
const isSmallest = k === 0;
if (isSmallest) return root.val;
root = root.right;
}
}
const moveLeft = (root, stack) => {
while (root !== null) {
stack.push(root);
root = root.left;
}
return stack.pop();
}