← Questions
Binary search tree iterator
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's AI-enabled coding round, last asked Jan 2026. It tests trees, bst and stacks.
Implement an iterator over a binary search tree that returns its values in ascending order. next() returns the next smallest value and has_next() says whether one remains. Each call should take amortized O(1) time, and the iterator may use only O(h) memory, where h is the height of the tree.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
BSTIterator(root: TreeNode | None)— sets up the iterator. -
next() -> int— returns the next smallest value; called only whenhas_next()is true. -
has_next() -> bool.
Example
7
/ \
3 15
/ \
9 20
it = BSTIterator(root)
it.next() -> 3
it.next() -> 7
it.has_next() -> True
it.next() -> 9
it.next() -> 15
it.next() -> 20
it.has_next() -> False
Constraints
-
0 <= number of nodes <= 10^5. - Up to
10^5calls in total.
Clarifying questions
- Can the tree change while it is being iterated?
- Is
next()ever called when nothing is left, and what should happen then? - Are values distinct?
What a strong answer covers
- The simple version: an inorder traversal into a list at construction,
O(1)per call butO(n)memory, which breaks the memory requirement. - The stack version: push the root and all its left descendants.
next()pops a node, then pushes its right child and that child's left descendants. - Why it is amortized
O(1): every node is pushed and popped exactly once over the whole iteration, though a single call can costO(h). -
O(h)memory for the stack. - Tests: empty tree, single node, a left-skewed and a right-skewed tree, interleaved
has_next()andnext()calls.
Follow-ups
- Add
peek(), which returns the next value without advancing. - Iterate in descending order, or support moving both forwards and backwards.
- Use
O(1)extra memory (Morris traversal) and say what it costs. - Merge two BST iterators to produce all values of two trees in sorted order.
Where it's asked
- Meta · AI-enabled coding · Last asked Jan 202660 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
What it tests
trees · bst · stacks · iterators
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.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
