Kth Smallest Element in a BST LeetCode solution in JavaScript

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
var kthSmallest = function (root, k) {
15
let stack = [];
16
while (root != null || stack.length > 0) {
17
while (root != null) {
18
stack.push(root);
19
root = root.left;
20
}
21
root = stack.pop();
22
if (--k == 0) break;
23
root = root.right;
24
}
25

26
return root.val;
27
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0