Kth Smallest Element in a BST
Pick the k-th smallest value in a binary search tree
DSA, Medium, Trees
Which structure or algorithm, and what does it cost.
You get a binary search tree tree. Your code may take the root node or the list. Each node has val, left and right, null when missing. Either is fine; no conversion is needed. The examples use a level-order list. It holds values row by row, left to right. Null marks a missing child. A missing node has no entries below it. Smaller values sit on the left, larger ones on the right, and no value repeats. You also get a whole number k. Return the k-th smallest value in the tree, counting the smallest as 1.
Examples
Constraints
- 1 <= number of nodes <= 30,000.
- 1 <= k <= number of nodes.
- Each value is a whole number between -100,000 and 100,000, and all values are different.
- The tree can be one long chain.
Your answer must contain
- The simple method and its cost; the best method and why it is correct; code; time and memory cost; a hand trace of example 1.
Target Aim for O(h + k) time, where h is the height of the tree.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
A search tree has a built-in order. Which walk through the tree lists the values from smallest to largest?
Hint 2 the approach
The left side comes first, then the node, then the right side. Do you need to visit every node to find the k-th?
Hint 3 the key step
Walk in order with a stack: go left as far as you can, pop a node and count it, then go right. Stop when the count reaches k.
Walkthrough
Full walkthrough brute force to best
Brute force
Collect every value in the tree, sort the values, and take the one at position k. This ignores the order that the tree already has. It costs O(n log n) time for the sort and O(n) memory for the list, and it reads the whole tree even for k = 1.
Best method
In a search tree, the left side of a node holds smaller values and the right side holds larger ones. A walk that visits the left side, then the node, then the right side lists the values from smallest to largest. This is the in-order walk. Run it with a stack so a long chain cannot overflow the call stack. Go left as far as possible and push each node. Pop one: it is the next smallest value. Count it. If the count is k, return it. Otherwise move to its right child and repeat. The walk stops as soon as it reaches the k-th value, so it never reads the rest of the tree.
Hand trace
Run on [12, 6, 18, 3, 9, 15, 24, 1, null, 7] with k = 4. The tree: 12 has children 6 and 18. Node 6 has children 3 and 9. Node 3 has a left child 1. Node 9 has a left child 7. Go left from 12: push 12, 6, 3, 1. Pop 1: k drops from 4 to 3, and its right child is missing. Pop 3: k drops to 2, and its right child is missing. Pop 6: k drops to 1, and we move to its right child 9. Go left from 9: push 9, 7. Pop 7: k drops to 0. Return 7.
Code
def kth_smallest(root, k):
node, stack = root, []
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
k -= 1
if k == 0:
return node.val
node = node.rightTime and memory
O(h + k) time: the walk goes down h levels to the smallest value, then takes about k steps. For a chain this is O(n). O(h) extra memory for the stack.
Common mistakes
- Counting k from 0. The smallest value is the 1st, so stop when the counter reaches k, not k + 1.
- Using a walk that visits the node before its sides. Only the in-order walk gives the values in sorted order.
- Dropping the move to the right child after popping a node. The values of the right side come next in the order, so skipping it loses them.