230 Kth Smallest Element in a BST
230. Kth Smallest Element in a BST
1. Question
2. Implementation
class Solution {
public int kthSmallest(TreeNode root, int k) {
int count = 1;
Stack<TreeNode> stack = new Stack<>();
TreeNode curNode = root;
while (curNode != null || !stack.isEmpty()) {
if (curNode != null) {
stack.push(curNode);
curNode = curNode.left;
}
else {
curNode = stack.pop();
if (count == k) {
return curNode.val;
}
++count;
curNode = curNode.right;
}
}
return -1;
}
}3. Time & Space Complexity
Last updated