Kth Smallest Element in a BST
Pattern: Kth smallest
An inorder walk visits a BST's values in increasing order. Do it iteratively with a stack and stop at the kth value visited.
The problem
Return the kth smallest value (k counts from 1) in a BST. [3, 1, 4, null, 2] with k = 1 gives 1. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- Which traversal is sorted?
- Do you need all of it?
- What is the first value an inorder walk visits?
Hints
Brute force, and why it fails
Collect the whole inorder and index it: O(n).
The key insight
Inorder is sorted, and an iterative walk can stop exactly at the kth value.
Dry run
| stack | 5 3 2 1 |
|---|
BST [5, 3, 6, 2, 4, null, null, 1], k = 3. Push 5, 3, 2, 1.
Step 1 of 3
The plan
loop: push the left chain; n = pop; k -= 1; if k == 0: return n.val; n = n.right
Complexity
- Time
O(h + k)- Space
O(h)
The walk does h steps down and k pops.
Edge cases
- k = 1: the minimum.
- k = n: the maximum.
- A chain.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> st = new ArrayDeque<>();
TreeNode n = root;
while (true) { // an inorder walk that stops at the kth value
while (n != null) { st.push(n); n = n.left; }
n = st.pop();
if (--k == 0) return n.val;
n = n.right;
}
}
}C++
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
stack<TreeNode*> st;
TreeNode* n = root;
while (true) { // an inorder walk that stops at the kth value
while (n != NULL) { st.push(n); n = n->left; }
n = st.top();
st.pop();
if (--k == 0) return n->val;
n = n->right;
}
}
};Python
class Solution:
def kthSmallest(self, root, k: int) -> int:
st, n = [], root
while True: # an inorder walk that stops at the kth value
while n:
st.append(n)
n = n.left
n = st.pop()
k -= 1
if k == 0:
return n.val
n = n.rightCommon mistakes
- Counting from 0.
- Walking the whole tree when k is small.