Binary Search Tree Iterator

medium

Implement an iterator over the in-order traversal of a binary search tree. The iterator starts positioned before the smallest value, hasNext() reports whether a next value exists, and next() returns the next-smallest value.

To exercise the iterator here, implement bstIteratorSequence(root): construct the iterator and repeatedly call next() while hasNext() is true, returning the list of emitted values (which is the tree's values in sorted order). The tree is given in level-order, using null for missing children.

The challenge is to do this in O(1) amortized time per next() call and O(height) memory — without flattening the whole tree first.

Hints

Inorder traversal of a BST returns values in sorted order — but an iterator must pause between them.
Use an explicit stack holding the left spine of the unvisited tree.
next() pops the top and pushes the left spine of its right subtree; hasNext() checks the stack.

Common doubts

A single next() can push a whole left spine, but across the entire traversal every node is pushed and popped exactly once, so the average is O(1).
It uses O(height) memory instead of O(n) — it never holds more than one root-to-node path at a time.
The nodes whose values are next in line but not yet returned, with the smallest on top.

Interview follow-ups

Keep a second stack (or a doubly-threaded structure); the two-stack design mirrors next() with the right spine.
The same stack works — inorder order is defined for any binary tree; it just isn't sorted.

Fun facts

  • This is the canonical way to make any recursive traversal resumable: replace the call stack with an explicit one.
  • The same pattern powers merge-style algorithms that walk two BSTs in lockstep.

Asked at

AmazonMicrosoftFacebookGoogle
Frequently Sometimes Occasionally
Example 1
Input: root = [7, 3, 15, null, null, 9, 20]
Output: [3, 7, 9, 15, 20]
Draining the iterator yields the values in ascending (inorder) order.
Example 2
Input: root = [2, 1, 3]
Output: [1, 2, 3]
next() returns 1, then 2, then 3; hasNext() is then false.
Constraints

- The number of nodes is in the range [0, 10^5] - 0 <= Node.val <= 10^6 - All Node.val are unique

Solve this problem →