Binary Search Tree Iterator (LeetCode 173): Solution and Explanation

Medium
Stack
Tree
Design
Binary Search Tree
Binary Tree
Iterator

Design an iterator over a binary search tree that returns values in ascending order. next() returns the next smallest value and hasNext() reports whether any remain. The goal is amortized constant time per call and memory proportional to the tree height, not its size.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The easy solution is to do a full in-order traversal in the constructor, store every value in a list, and walk an index through it. That makes each call O(1), but it uses O(n) memory and does all the work up front even if the caller only wants the first few values.

Instead, pause the in-order traversal and resume it on demand. Recursive in-order traversal keeps a call stack of nodes whose left subtree is being visited. If you simulate that stack yourself, you can stop after producing each value. The smallest value in any subtree is found by walking left as far as possible, so the stack starts with the left spine from the root.

When next() pops a node, that node is the current smallest. Its successor is either the leftmost node of its right subtree, or, if it has no right child, the next node already waiting on the stack. Pushing the left spine of the right child handles both cases at once. The stack never holds more than one root-to-leaf path, so memory is O(h).

Approach: Controlled in-order traversal with a stack

  1. In the constructor, create an empty stack and call _push_left(root).
  2. _push_left(node) walks down left children, pushing each node, until it reaches None.
  3. In next(), pop the top node; it holds the smallest value not yet returned.
  4. Call _push_left(node.right) so the right subtree's smallest values are ready for later calls.
  5. Return node.val.
  6. hasNext() simply returns whether the stack is non-empty, because any node still on the stack is a value that has not been returned yet.

Step-by-step example

BST with root 7, left child 3, right child 15, and 15 having children 9 and 20
  1. Constructor pushes the left spine: stack is [7, 3].
  2. next() pops 3, which has no right child, and returns 3. Stack is [7].
  3. next() pops 7, then pushes the left spine of 15, giving stack [15, 9], and returns 7.
  4. next() pops 9 and returns it. Then next() pops 15, pushes 20, and returns 15.
  5. next() pops and returns 20. The stack is empty, so hasNext() returns false. The values came out as 3, 7, 9, 15, 20.

Code: Python, Java, C++

1class BSTIterator:
2    def __init__(self, root: Optional[TreeNode]):
3        self.stack = []
4        self._push_left(root)
5
6    def _push_left(self, node):
7        while node:
8            self.stack.append(node)
9            node = node.left
10
11    def next(self) -> int:
12        node = self.stack.pop()
13        self._push_left(node.right)
14        return node.val
15
16    def hasNext(self) -> bool:
17        return len(self.stack) > 0

Time and space complexity

Time

O(1) amortized per call

Each node is pushed once and popped once over the whole iteration, so n calls to next() cost O(n) in total. A single call can take O(h) when it pushes a long spine, but the average is constant. hasNext() is always O(1).

Space

O(h)

The stack holds at most one path from the root down to a leaf, where h is the tree height (O(log n) for a balanced tree and O(n) for a skewed one).

Other approaches

Flatten into a list (time O(n) build, O(1) per call, space O(n))

Do a full in-order traversal in the constructor and serve values from an array. Every call is strictly O(1), but memory is O(n) and all the work happens up front.

Morris traversal (time O(1) amortized, space O(1))

Temporarily thread right pointers of predecessor nodes so the traversal needs no stack at all. It gets O(1) extra space but mutates the tree while iterating, which is risky if anyone else reads it.

Common mistakes

  • Pushing the entire right subtree instead of just its left spine. Only the path to the smallest node is needed; pushing more breaks the O(h) memory bound and the ordering.
  • Forgetting to push the right child's spine after popping a node, so all values in right subtrees are skipped.
  • Calling _push_left(node.right) before popping, or pushing node.left again, which revisits values that were already returned.
  • Claiming every next() call is worst-case O(1). It is amortized; one call may push up to h nodes.

Frequently asked questions

Why is next() amortized O(1)?

Across a full iteration, every node is pushed onto the stack exactly once and popped exactly once. Spreading those 2n operations over n calls gives constant time on average, even though one call can do O(h) work.

Why does the iterator use O(h) memory?

The stack only ever contains the nodes on one path from the root, those whose left side is being explored. That path is at most as long as the tree height.

Can you implement a BST iterator without a stack?

Yes, with Morris traversal, which threads temporary links to predecessors. It uses O(1) extra space but modifies the tree during iteration.

How does hasNext() know when to stop?

An empty stack means no node is waiting to be visited and no right subtree is pending, so the traversal is complete.