Kth Smallest Element in a BST
Since a BST's inorder traversal visits values in sorted order, the kth smallest value is simply the kth value that traversal produces. Counting as the traversal proceeds -- and stopping the instant the count reaches k -- avoids ever needing to build the full sorted list.
Problem in simple words
Given a binary search tree and a number k, find the kth smallest value it contains (1st smallest, 2nd smallest, and so on).
Core idea
Sorted order plus a running counter is all a 'kth smallest' question ever needs -- a BST's inorder traversal produces that sorted order for free, so just count until you reach k.
How the algorithm thinks
- 1
Count this node's sorted position
VISITInorder order is sorted order, so a running counter incremented at each visit tells you exactly which sorted position you're currently at.
Watch: The current node's value and the running count.
- 2
The counter reaches k
FOUNDThe count-th value visited in sorted order is, by definition, the count-th smallest value in the whole tree -- no further searching is needed once this matches k.
Watch: The matching node's value and that it equals k.
- 3
Stop immediately once found
RETURNContinuing to traverse after the answer is already known would only visit larger values that can't possibly still be relevant.
Watch: Which pending recursive calls short-circuit once the result is set.
Step-by-step logic
- -Initialize count to 0 and result to null (or 'not found yet').
- -Recursively visit the left subtree first -- but stop immediately if result has already been set.
- -At the current node, increment count by 1.
- -If count now equals k, record the current node's value as the result and stop.
- -Otherwise, recursively visit the right subtree (again stopping immediately if result gets set partway through).
- -Once the traversal ends (naturally or via early stop), result holds the answer.
Complexity
Time O(h + k)·Space O(h)
In the best case, the traversal stops as soon as the kth value is found; it visits at most h (the tree's height) nodes just to reach the leftmost value, plus up to k nodes total before stopping.
Implementation
This is the JavaScript implementation that generates the simulator timeline.
function kthSmallest(root, k) {
let count = 0;
let result = null;
function inorder(node) {
if (node === null || result !== null) return;
inorder(node.left);
if (result !== null) return;
count++;
if (count === k) {
result = node.val;
return;
}
inorder(node.right);
}
inorder(root);
return result;
}Common mistakes
Pause before the next step and name the state change you expect.
Watch the active node, recursive call stack, and completed branches and match it to the highlighted code line.
Say the rule that never breaks (the invariant) out loud: what remains true before and after this step?
- -Step 1: inorder reaches 1 first (leftmost node). count becomes 1. Since k=1, count === k -- 1 is the answer, stop immediately.
- -(If k were 3 instead): Step 1: reach 1, count=1 (not yet 3). Step 2: reach 2, count=2 (not yet 3). Step 3: reach 3 (the root), count=3 -- matches k=3, so 3 is the answer, stop immediately without ever visiting 4.
- - What should this function promise to do?
- - Where does the recursion stop?
- - Which smaller problem can you trust?
- - How does current work connect with the smaller answer?
Build the reasoning before opening the simulator
Turn the mental model into a short decision checklist, then compare it with the execution timeline.