forked from jyxia/LeetCode-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path230-kthSmallestElementinBST.js
49 lines (45 loc) · 1.02 KB
/
230-kthSmallestElementinBST.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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* Key: just use inorderTraversal to traverse the tree. Inorder traversal
* travels the node in a ascending order because it is a BST...
*
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function(root, k) {
var stack = [];
var node = root;
while (node || stack.length > 0) {
if (node) {
stack.push(node);
node = node.left;
} else {
node = stack.pop();
k--;
if (k === 0) return node.val;
node = node.right;
}
}
};
// second try
var kthSmallest = function(root, k) {
var stack = [];
while (root || stack.length > 0) {
while (root) {
stack.push(root);
root = root.left;
}
root = stack.pop();
k--;
if (k === 0) return root.val;
root = root.right;
}
return 0;
};