stack nodes waiting for their turn · top on the right · badges on the tree = pop order n
Popped in order sorted, smallest first
public int kthSmallest(TreeNode root, int k) { int n = 0; Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode cur = root; while (cur != null || !stack.isEmpty()) { while (cur != null) { stack.push(cur); cur = cur.left; } cur = stack.pop(); n++; if (n == k) { return cur.val; } cur = cur.right; } return -1; // never reached: 1 <= k <= n}
- k
- —
- n
- 0
- cur
- —
- stack
- []
Why it works
- Brute force collects all values, sorts them and indexes
k − 1: O(n log n) time, O(n) space, and it ignores the BST order completely. - In-order traversal of a BST visits values in sorted order. So the k-th node popped is the answer. The stack holds the path of left turns still waiting: a node is popped only after everything smaller than it.
- Cost: the walk first dives down the left spine (up to h pushes), then pops k nodes, each followed by at most a short dive: O(h + k) time. The stack never holds more than one path: O(h) space.
- Pitfall: counting when a node is pushed instead of when it is popped. Pushes happen top-down along a path, which is not sorted; only pops come out in order.
- Follow-up: if the tree changes often and k-th queries are frequent, store the size of each subtree in its node; then each query walks one path, O(h).