BST iterator
A BST iterator returns values in sorted order one at a time. Keep a stack with the path of nodes still to visit: push the far-left chain of the root; next() pops a node and pushes the far-left chain of its right child. Each call is O(1) on average with O(h) memory. Two such walks side by side merge two BSTs.
How to recognise it
- Values of a BST are needed one at a time, in order.
- Merging two BSTs, or walking one in both directions.
- Turning a BST into a sorted list.
The stack is a paused inorder walk
init(root): pushLeft(root)
next(): n = pop; pushLeft(n.right); return n.val
hasNext(): stack is not empty
pushLeft(n): while n: push n; n = n.left
The rule that makes a BST, and how it compares with a heap, is on the Structures page.
Uses
| Problem | How |
|---|---|
| merge two BSTs | two iterators; take the smaller top each time |
| flatten to a sorted list | inorder; hang each node on the previous one's right |
| two sum in a BST | one forward and one backward iterator, like two pointers |
Common mistakes
- Pushing the whole tree at the start, which uses O(n) memory.
- Forgetting to push the right child's left chain after popping.
Problems
- Binary Search Tree Iteratormediumguide ready
- Merge two BSTmediumguide ready
- Flatten BST to sorted listmediumguide ready