Kth Smallest Element in a BST
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given the root of a binary search tree and an integer k, return the k-th smallest value in the tree (counting from 1).
Understand the problem
- In a BST, everything in a node's left subtree is smaller than it, and everything in its right subtree is larger.
- The
k-th smallest is the value you'd get at positionkif you sorted all the tree's values:k = 1is the smallest,k = 2is the second smallest, and so on.
Example 1
Input: root = [5, 3, 6, 2, 4, null, null, 1], k = 3
Output: 3
5
/ \
3 6
/ \
2 4
/
1Sorted, the values are 1, 2, 3, 4, 5, 6. The 3rd one is 3.
Example 2
Input: root = [3, 1, 4, null, 2], k = 1
Output: 1k = 1 asks for the smallest value: 1.
How trees are written in the tests: level by level, top to bottom, left to right, with null for a missing child.
Constraints
1 <= k <= number of nodes <= 10^4
Note
Follow-up: if the tree changes often (inserts and deletes) and you're asked for the k-th smallest often, how would you speed it up?
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Walk the BST in order (left, node, right), which visits the values from smallest to largest, and stop at the k-th one.
The simple approach (and its cost)
Collect all the values into an array, sort it, and return arr[k - 1]. It's correct, but it visits every node and sorts them: O(n log n), and it ignores the BST's ordering entirely.
The key insight
A BST already keeps its values in order: smaller on the left, larger on the right. If you visit:
- the left subtree first (all smaller values),
- then the node itself,
- then the right subtree (all larger values),
you visit the values in sorted order. This is an in-order traversal. So the k-th node you visit is the k-th smallest, and you can stop right there.
Why a stack instead of recursion? It makes stopping early easy. The stack remembers the nodes we've passed on the way down, the same way the recursion's call stack would:
- From the current node, go left as far as possible, pushing each node onto the stack.
- Pop a node: nothing smaller is left unvisited, so it's the next smallest. Count it.
- Move to its right child (the values just above it), and repeat.
Step by step
root = [5, 3, 6, 2, 4, null, null, 1], k = 3:
| Action | Stack (bottom → top) | Visited (count) |
|---|---|---|
go left from 5: push 5, 3, 2, 1 | 5, 3, 2, 1 | |
pop 1, right is empty | 5, 3, 2 | 1 (1) |
pop 2, right is empty | 5, 3 | 2 (2) |
pop 3 | 5 | 3 (3) → stop |
The answer is 3. We never touched 4, 5's right side, or 6.
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(h + k), where
his the tree's height: we go down one path to the smallest value, then visitknodes. - Memory: O(h) for the stack.
Common mistakes
- Off by one.
kcounts from 1. Count downkand stop when it reaches 0, or count up and stop atk. - Visiting right before left. That gives the values in decreasing order (k-th largest instead).
- Traversing the whole tree when you could stop. Correct, but wastes time when
kis small.
Going deeper
The follow-up: store in each node the size of its left subtree. At a node with leftSize smaller values below it on the left: if k <= leftSize, go left; if k === leftSize + 1, it's this node; otherwise go right with k - leftSize - 1. That's O(h) per query, like a binary search. Inserts and deletes update the sizes along their path.
Reference solution
/**
* @param {TreeNode | null} root
* @param {number} k
* @return {number}
*/
export default function kthSmallest(root, k) {
// In-order (left, node, right) visits a BST from smallest to largest.
// Our own stack plays the role of recursion, so we can stop the moment we hit k.
const stack = []
let node = root
while (node || stack.length > 0) {
// 1. Go left as far as possible, remembering the path.
while (node) {
stack.push(node)
node = node.left
}
// 2. Nothing smaller is left unvisited: this is the next smallest value.
node = stack.pop()
k--
if (k === 0) return node.val
// 3. The values just above it are in its right subtree.
node = node.right
}
return -1
}export default function kthSmallest(root: TreeNode | null, k: number): number {
// In-order (left, node, right) visits a BST from smallest to largest.
// Our own stack plays the role of recursion, so we can stop the moment we hit k.
const stack: TreeNode[] = []
let node = root
while (node || stack.length > 0) {
// 1. Go left as far as possible, remembering the path.
while (node) {
stack.push(node)
node = node.left
}
// 2. Nothing smaller is left unvisited: this is the next smallest value.
const current = stack.pop()!
k--
if (k === 0) return current.val
// 3. The values just above it are in its right subtree.
node = current.right
}
return -1
}def kth_smallest(root: TreeNode | None, k: int) -> int:
# In-order (left, node, right) visits a BST from smallest to largest.
# Our own stack plays the role of recursion, so we can stop the moment we hit k.
stack = []
node = root
while node or stack:
# 1. Go left as far as possible, remembering the path.
while node:
stack.append(node)
node = node.left
# 2. Nothing smaller is left unvisited: this is the next smallest value.
node = stack.pop()
k -= 1
if k == 0:
return node.val
# 3. The values just above it are in its right subtree.
node = node.right
return -1