BST Iterator
Binary Search Tree Iterator is LeetCode 173 (Medium). Build a class BSTIterator over the root of a BST that hands out the values in sorted (inorder) order:
next()returns the next smallest value. The first call returns the smallest.hasNext()returns whether any value is left.next()is only called when a value is left.
Follow-up: both calls in average O(1) time, using only O(h) memory, where h is the height of the tree.
- The number of nodes in the tree is in the range [1, 10⁵].
- 0 <= Node.val <= 10⁶
- At most 10⁵ calls will be made to hasNext, and next.
Intuition
A BST iterator is an inorder traversal that pauses between values. A paused traversal does not need the whole sorted list; it only needs the nodes it has walked past but not returned yet. Keep those on a stack.
- What the stack holds: a path of nodes still waiting to be returned, with the smallest on top.
- What comes after a node: its right subtree, starting from that subtree's leftmost node. Every value in there is larger than the node but smaller than the node waiting below it on the stack.
The stack never holds more than one root-to-node path, so memory is O(h).
An iterator over a tree, or "return the next item in sorted order on demand", is a traversal with an explicit stack that you advance one step per call. The same structure solves Two Sum IV on a BST (two iterators, one ascending and one descending), Kth Smallest Element in a BST, and merging two BSTs into one sorted list.
Approach
Before reading on: for the tree [7, 3, 15, null, null, 9, 20], which nodes must you have seen before you can return 3? After returning 7, which node comes next, and how do you reach it without starting from the root again?
Two ways to solve it
Pause the inorder traversal: keep the nodes still waiting on a stack and advance one value per call.
- Memory: one root-to-node path, O(h).
- Setup: only the left spine, O(h).
- Per call: O(1) on average, up to O(h) once.
Meets the follow-up, so interviewers expect it.
Run a full inorder traversal in the constructor, store every value, and hand them out with an index.
- Memory: all n values.
- Setup: O(n) before the first call.
- Per call: a plain O(1) index step.
Accepted, but it misses the O(h) memory follow-up.
The stack version uses memory for one path instead of every value, which is what the follow-up asks for, so the steps, code and live demo below follow it. The flattened version is the usual first answer; its code comes after the demo.
Push the left spine in the constructor
Start at the root, push the node, move to its left child, and repeat until there is none. The smallest value is the leftmost node, so it ends up on top of the stack, and its ancestors wait below it in order.
next(): pop the top, then push its right child's spine
The popped node is the answer. Before returning it, run the same push loop from node.right. Those values come before every node still on the stack, so they must sit above them; the leftmost of them ends up on top. If there is no right child, push nothing: the next answer is already on top.
hasNext(): check the stack
A value is left exactly when the stack is not empty, so hasNext() is one comparison.
Code in Python, C++ and Java
Flatten the BST to a sorted list
The constructor runs a recursive inorder traversal and stores every value in vals. next() returns vals[i] and moves the index on; hasNext() checks whether the index has reached the end.
Common pitfalls
Pushing only the right child
if node.right:
self.stack.append(node.right)self._push_left(node.right)
The right child's own left descendants are smaller than it, so they must come out first. In [4, 2, 6, 1, 3, 5], after 4 this returns 6, and 5 is never returned at all.
Following right pointers when filling the stack
while node:
self.stack.append(node)
node = node.rightwhile node:
self.stack.append(node)
node = node.leftInorder starts at the leftmost node. Walking right puts the largest values on the stack first, and the first next() returns the maximum instead of the minimum.
Edge cases
The constructor pushes every node, so the stack holds n nodes. That is still O(h): in this tree the height is n.
No node has a left child, so the stack never holds more than one node at a time.
Complexity
BST Iterator FAQ
How do you make a BST iterator that returns values in descending order?
Mirror the left and right directions. Push the right spine (move to node.right until there is none), and after popping a node, push the right spine of node.left. The largest value is then on top first. Two Sum IV on a BST uses one ascending and one descending iterator together.
Can this be solved without a stack?
Yes, with a Morris traversal: it temporarily links each node's inorder predecessor back to it, so it can climb back up without a stack, using O(1) extra memory. It changes the tree while iterating and is much harder to get right, so the stack version is the usual answer.