Skip to problem
←

Binary Search Tree Iterator

Medium 0 attempts

Design an iterator over a binary search tree that walks its values in ascending order. It should expose next(), which returns the next-smallest value each time it's called, and hasNext(), which reports whether any values remain — with next() running in amortized O(1) time and hasNext() in O(1) time while using only O(h) extra memory, where h is the tree's height.

hasNext() must not advance the iterator. Calls to next() occur only when hasNext() is true.

Function contract

Implement class BSTIterator. Its constructor receives a root node with val, left, and right fields; the runner converts the shown level-order array to that tree. Operations are [method] calls on the same instance.

Output: next() returns the next-smallest number; hasNext() returns a boolean without advancing. Output lists method results in call order. Each test creates a fresh iterator.

Example 1

Input
constructorArgs = [[7,3,15,null,null,9,20]]
operations = [["next"],["next"],["hasNext"],["next"],["next"],["next"],["hasNext"]]
Output
[3,7,true,9,15,20,false]

Example 2

Input
constructorArgs = [[1]]
operations = [["hasNext"],["next"],["hasNext"]]
Output
[true,1,false]
Visual Aid
Read the tree in ascending order
7315920next(): 3 → 7 → 9 → 15 → 20

Each next() advances one step through this sequence. hasNext() only reports whether another step is available.

Constraints
  • 1 <= number of nodes <= 10^5
  • 0 <= Node.val <= 10^6
  • At most 10^5 calls to next() and hasNext()

Controlled Inorder with Stack

Maintain a stack of left-spine nodes. On next(), pop and push right subtree's left spine.

javascript
class BSTIterator {
  constructor(root) {
    this.stack = [];
    this._pushLeft(root);
  }
  _pushLeft(node) {
    while (node) {
      this.stack.push(node);
      node = node.left;
    }
  }
  next() {
    const node = this.stack.pop();
    this._pushLeft(node.right);
    return node.val;
  }
  hasNext() {
    return this.stack.length > 0;
  }
}

Time: O(h) initialization; O(1) amortized per next() across a traversal, with O(h) worst case for one call; O(1) per hasNext(). Space: O(h)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript