LeetCode #173 Medium

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.

Constraints
  • 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.
bststackdesign
Open on LeetCode ↗
02

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).

How to spot this pattern

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.

03

Approach

Try it first

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?

1

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.

2

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.

3

hasNext(): check the stack

A value is left exactly when the stack is not empty, so hasNext() is one comparison.

04

Code in Python, C++ and Java

▶1class BSTIterator:
▶2 def __init__(self, root: Optional[TreeNode]):
▶3 self.stack = []
▶4 self._push_left(root)
▶5 
▶6 def _push_left(self, node: Optional[TreeNode]) -> None:
▶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
7315920stack7topoutputpush 7 → go left to 3
stack[7]bottom → top
Constructor. Walk left from the root, pushing every node, to reach the smallest value. Push 7. It has a left child 3, which is smaller still, so keep going left.
7315920stack73topoutputpush 3 → no left child, stop
stack[7, 3]bottom → top
Push 3: it is smaller than 7, so it must come out first and sits above it. It has no left child, so no value still waiting is smaller: 3 is the next value, on top.
7315920stack7topoutput3pop 3 → next() returns 3, no right child
stack[7]bottom → top
next()3
next() pops 3, the smallest value not yet returned, and returns it. It has no right child, so nothing is pushed. The next value, 7, is already on top.
7315920stackemptyoutput37pop 7 → next() returns 7
stackemptybottom → top
next()7
next() pops 7, the smallest value not yet returned, and returns it. Its right subtree holds the values just above 7, so those come next: push that subtree's left spine before returning.
7315920stack15topoutput37push 15 → go left to 9
stack[15]bottom → top
Push 15. It has a left child 9, which is smaller still, so keep going left.
7315920stack159topoutput37push 9 → no left child, stop
stack[15, 9]bottom → top
Push 9: it is smaller than 15, so it must come out first and sits above it. It has no left child, so no value still waiting is smaller: 9 is the next value, on top.
7315920stack159topoutput37hasNext() → true
stack[15, 9]bottom → top
hasNexttrue
hasNext() returns true. The stack still holds 2 nodes waiting to be returned.
7315920stack15topoutput379pop 9 → next() returns 9, no right child
stack[15]bottom → top
next()9
next() pops 9, the smallest value not yet returned, and returns it. It has no right child, so nothing is pushed. The next value, 15, is already on top.
7315920stack15topoutput379hasNext() → true
stack[15]bottom → top
hasNexttrue
hasNext() returns true. The stack still holds 1 node waiting to be returned.
7315920stackemptyoutput37915pop 15 → next() returns 15
stackemptybottom → top
next()15
next() pops 15, the smallest value not yet returned, and returns it. Its right subtree holds the values just above 15, so those come next: push that subtree's left spine before returning.
7315920stack20topoutput37915push 20 → no left child, stop
stack[20]bottom → top
Push 20. It has no left child, so no value still waiting is smaller: 20 is the next value, on top.
7315920stack20topoutput37915hasNext() → true
stack[20]bottom → top
hasNexttrue
hasNext() returns true. The stack still holds 1 node waiting to be returned.
7315920stackemptyoutput3791520pop 20 → next() returns 20, no right child
stackemptybottom → top
next()20
next() pops 20, the smallest value not yet returned, and returns it. It has no right child, so nothing is pushed. The stack is now empty.
7315920stackemptyoutput3791520hasNext() → false
stackemptybottom → top
hasNextfalse
hasNext() returns false. The stack is empty: every value has been returned.
05

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.

▶1class BSTIterator:
▶2 def __init__(self, root: Optional[TreeNode]):
▶3 self.vals = []
▶4 self.i = 0
▶5 self._inorder(root)
▶6 
▶7 def _inorder(self, node: Optional[TreeNode]) -> None:
▶8 if node:
▶9 self._inorder(node.left)
▶10 self.vals.append(node.val)
▶11 self._inorder(node.right)
▶12 
▶13 def next(self) -> int:
▶14 self.i += 1
▶15 return self.vals[self.i - 1]
▶16 
▶17 def hasNext(self) -> bool:
▶18 return self.i < len(self.vals)
06

Common pitfalls

Pushing only the right child

✗ Wrong
if node.right:
    self.stack.append(node.right)
✓ 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

✗ Wrong
while node:
    self.stack.append(node)
    node = node.right
✓ Right
while node:
    self.stack.append(node)
    node = node.left

Inorder 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.

07

Edge cases

Tree that leans fully left

The constructor pushes every node, so the stack holds n nodes. That is still O(h): in this tree the height is n.

Tree that leans fully right

No node has a left child, so the stack never holds more than one node at a time.

08

Complexity

Time
O(1) average per call
Space
O(h)
Every node is pushed once and popped once over all the calls, so n calls to next() cost O(n) in total. A single call can push up to h nodes. The constructor is O(h).
09

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.