-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkth-smallest-element-in-a-bst.js
More file actions
55 lines (52 loc) · 1.09 KB
/
kth-smallest-element-in-a-bst.js
File metadata and controls
55 lines (52 loc) · 1.09 KB
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
50
51
52
53
54
55
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function (root, k) {
// 中序遍历二叉搜索树相当与遍历有序数组
// 递归 需要遍历整棵树
let counter = 0;
let rankKNum = 0;
const dfs = (root) => {
if (!root) return null;
dfs(root.left);
counter++;
if (k === counter) {
rankKNum = root.val;
}
dfs(root.right);
};
dfs(root);
return rankKNum;
// 迭代 无需遍历整棵树
// return inOrderIterate(root, k);
};
function inOrderIterate(root, k) {
const stack = [];
let curr = root,
node = null;
while (stack.length || curr) {
while (curr) {
stack.push(curr);
curr = curr.left;
}
node = stack.pop();
k--;
if (k === 0) {
break;
}
if (node.right) {
curr = node.right;
}
}
return node.val;
}