Lazy in-order BST iterator
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Apple's technical phone screen, last asked Feb 2026. It tests trees, iterators and stacks.
Write an iterator over a binary search tree that returns its values in sorted order, one at a time. It must be lazy: don't copy the tree into a list. Memory should be proportional to the tree's height. Then make it safe when the tree changes or several threads use it.
Part 1: the iterator
Unless you agree on a different interface with the interviewer, assume:
-
BSTIterator(root): prepares the iterator. -
next() -> int: the next smallest value. Raises when there is none. -
has_next() -> bool.
Example
tree: 7
/ \
3 15
/ \
9 20
next() -> 3, next() -> 7, has_next() -> True, next() -> 9,
next() -> 15, next() -> 20, has_next() -> False
Part 2: concurrency
The tree is shared. Other threads insert and delete while iterators are open, and one iterator may be called from several threads. Explain, and sketch in code, how you keep this correct.
Constraints
- Up to
10^5nodes; the tree may be unbalanced. -
next()is amortized O(1); memory is O(height).
Clarifying questions
- If the tree changes during iteration, should the iterator fail, show a snapshot, or show live changes?
- Are reads much more common than writes?
- Can one iterator really be shared by threads, or does each thread have its own?
What a strong answer covers
- A stack of the left spine: pop a node, then push the left spine of its right child. Why that is amortized O(1) per call.
- Part 2 options and their costs: fail-fast with a modification counter, a read-write lock around the tree, a lock inside the iterator so
has_nextandnextare atomic together, or snapshot iteration over a persistent (copy-on-write) tree. - Why a
has_next()thennext()pair is a race between threads, and an API that avoids it (one call that returns the value or nothing).
Follow-ups
- Support
peek(). - Iterate in reverse order.
- Seek: start at the first value at or above a given key.
Where it's asked
- Apple · Technical phone screen · Last asked Feb 2026
What it tests
trees · iterators · stacks · concurrency
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
