Kth Smallest Element in a BST
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3class Solution {
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode curr = root;
while (curr != null) {
stack.offerLast(curr);
curr = curr.left;
}
int num = 0;
while (! stack.isEmpty()) {
curr = stack.pollLast();
if (++num == k) return curr.val;
curr = curr.right;
while (curr != null) {
stack.offerLast(curr);
curr = curr.left;
}
}
return -1;
}
}