Kth Smallest Element in a BST
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Return the k-th smallest value in a binary search tree.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1What order do you get from visiting left, node, right in a BST?
- Hint 2Count the nodes as you visit them and stop at k.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
A phone book stored as a tree where smaller names are always on the left. Reading "everything on the left first, then this entry, then everything on the right" gives the whole book in alphabetical order, with no sorting. To find the 3rd name, read in that order and stop at the third.
- The obvious way
Collect all values, sort them, take the k-th: O(n log n).
- The key insight
An in-order walk of a BST is already sorted. Do it with a stack so you can stop early: dive left as far as possible pushing nodes, pop one (that is the next smallest), count it, then move to its right child and dive left again. The k-th pop is the answer.
- The algorithm
- Stack empty; current = root; counter = 0.
- Go as far left as possible, pushing every node on the way.
- Pop a node: counter + 1. Counter equals k? That node's value is the answer.
- Otherwise move to the popped node's right child and repeat.
Watch it run
Exampletree = [5, 3, 6, 2, 4, null, null, 1], k = 3
Dive left from 5: 5, 3, 2, 1, pushing each. The leftmost node is 1.
stack: 5, 3, 2, 1
Where people slip
- It is the k-th SMALLEST: in-order on a BST is ascending. For the k-th largest do the walk right-first.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def kth_smallest(root, k):
stack = []
node = root
while stack or node:
while node: # go as far left as possible
stack.append(node)
node = node.left
node = stack.pop() # the next smallest value
k -= 1
if k == 0:
return node.val
node = node.rightNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.