← Questions

Binary search tree iterator

0
MetaCodingLast asked Jan 2026

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 when has_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^5 calls 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 but O(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 cost O(h).
  • O(h) memory for the stack.
  • Tests: empty tree, single node, a left-skewed and a right-skewed tree, interleaved has_next() and next() 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

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