Skip to content

Commit 69b5699

Browse files
authored
Create 230-kth-smallest-element-in-a-bst.js
1 parent e0be51f commit 69b5699

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

230-kth-smallest-element-in-a-bst.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @param {number} k
12+
* @return {number}
13+
*/
14+
const kthSmallest = function (root, k) {
15+
const st = []
16+
while (root !== null) {
17+
st.push(root)
18+
root = root.left
19+
}
20+
while (k !== 0) {
21+
const n = st.pop()
22+
k--
23+
if (k === 0) return n.val
24+
let right = n.right
25+
while (right !== null) {
26+
st.push(right)
27+
right = right.left
28+
}
29+
}
30+
return -1
31+
}

0 commit comments

Comments
 (0)