Given the root of a binary search tree and an integer k (1 <= k <= number of nodes), return the k-th smallest value in the BST.
The tree is given in level-order (breadth-first), using null for missing children.
Input: root = [5, 3, 6, 2, 4], k = 3 Output: 4 Inorder is 2, 3, 4, 5, 6; the 3rd smallest is 4.
Input: root = [5, 3, 6, 2, 4], k = 1 Output: 2 The smallest value.
- The number of nodes n is in the range [1, 10^4] - 1 <= k <= n - 1 <= Node.val <= 10^4 - root is a valid BST
An inorder traversal of a BST visits values in ascending order, so the k-th smallest is simply the k-th node of an inorder walk. The optimization: don't build the whole sorted list — do an iterative inorder and stop the moment you've popped k nodes.
“Is k 1-indexed?”
Yes — k = 1 is the smallest value.
“Is k always valid?”
Yes — 1 <= k <= number of nodes.
Inorder gives the BST's values in sorted order, so the k-th smallest is the k-th node I visit inorder.
I do an iterative inorder and return as soon as I've popped k nodes, so I don't traverse the whole tree.
Worked example — BST [5, 3, 6, 2, 4], k = 3
inorder: 2, 3, 4, 5, 6 3rd smallest = 4
The k-th node visited inorder is exactly the k-th smallest.
Iterative inorder lets you halt after k pops instead of traversing everything.
You only descend one spine and pop k nodes.
| Full inorder + index | Iterative inorder, stop at k | |
|---|---|---|
| Idea | Collect all values, take index k-1 | Pop nodes until the k-th |
| Time | O(n) | O(height + k) |
| Space | O(n) | O(height) |
Both use the sorted-inorder property; the iterative version stops early. Full code is in the Approaches selector below.
Key takeaway
Inorder yields ascending values, so the k-th smallest is the k-th inorder node. An iterative inorder stops after k pops — O(height + k), O(height) space.
iterative inorder:
pop the next-smallest node; k -= 1
if k == 0: return that node's value