Kth Smallest Element in a BST
Master this topic with zero to advance depth.
Kth Smallest Element in a BST
Find kth val.
Level I: Inorder Traversal to Array
Intuition
As with any BST problem, the inorder traversal gives us the elements in strictly increasing order. We can perform a full inorder traversal, store the results in an array, and then simply return the element at index k-1.
Thought Process
- Traverse the tree (Left, Node, Right).
- Append values to a list.
- Return
list[k-1].
Detailed Dry Run
| Tree | Inorder Array | k | Result |
|---|---|---|---|
| [3,1,4,null,2] | [1, 2, 3, 4] | 1 | 1 |
Level II: Divide and Conquer (using Node counts)
Intuition
If we can efficiently count the number of nodes in a subtree, we can determine whether the -th smallest element lies in the left subtree, is the root itself, or lies in the right subtree.
Logic
- Let
L = countNodes(root.left). - If
k == L + 1:root.valis the result. - If
k <= L: Search in the left subtree. - If
k > L + 1: Search in the right subtree for the(k - L - 1)-th smallest element.
Detailed Dry Run
k=1, L=2 (nodes in left). k<=L -> Search Left. L=1 (at next level). k<=L -> Search Left. L=0. k=1, L=0 -> k=L+1 -> Result found.
Level III: Optimal (Iterative Inorder with Early Exit)
Intuition
Thought Process
We don't need to visit all nodes if is small. By using an iterative inorder traversal with a stack, we can visit nodes one by one in increasing order. As soon as we reach the -th node, we return its value and stop the traversal.
Complexity
- Time: where is the height of the tree.
- Space: for the stack.
Detailed Dry Run
| Stack | Current Node | k-count | Action |
|---|---|---|---|
| [3, 1] | null | 0 | Pop 1, Push 2 |
| [3] | 2 | 1 | Pop 1 was 1st smallest. |
| [3] | null | 1 | Pop 2, k reaches 1 (if k=2) |
⚠️ Common Pitfalls & Tips
Be careful with the condition. Since is 1-indexed (1st smallest), we decrement and check k == 0 immediately after popping.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.