sagelearnai

Binary Search Tree Iterator

Difficulty: Medium · Pattern: Trees & BST · LeetCode #173

Implement BSTIterator, which iterates over a BST in inorder (ascending) order:

  • BSTIterator(root): initialize with the tree's root.
  • next(): return the next smallest value.
  • hasNext(): return whether more values remain.

next() and hasNext() should run in amortized O(1) time using O(h) memory, so you may not flatten the whole tree into an array.

Example

text
BSTIterator([7,3,15,null,null,9,20])
next() → 3, next() → 7, hasNext() → true, next() → 9,
hasNext() → true, next() → 15, hasNext() → true, next() → 20, hasNext() → false

Hints

  1. Take the iterative inorder traversal and pause it between visits.
  2. The stack holds the "left spine" of the part of the tree you haven't visited yet.

Approach

Keep a stack and a helper pushLeft(node) that pushes node, node.left, node.left.left, and so on.

  • Constructor: pushLeft(root).
  • next(): pop the top (the smallest unvisited value), then pushLeft(popped.right), and return the popped value.
  • hasNext(): the stack is non-empty.

Each node is pushed and popped exactly once over the whole iteration, so n calls to next() cost O(n) total: amortized O(1). The stack never holds more than one root-to-leaf path: O(h).

Complexity

Time: amortized O(1) per call. Space: O(h).

Python solution
class BSTIterator:
    def __init__(self, root):
        self.stack = []
        self._push_left(root)

    def _push_left(self, node):
        while node:
            self.stack.append(node)
            node = node.left

    def next(self):
        node = self.stack.pop()
        self._push_left(node.right)
        return node.val

    def hasNext(self):
        return bool(self.stack)
JavaScript solution
class BSTIterator {
  constructor(root) { this.stack = []; this.pushLeft(root); }
  pushLeft(node) { while (node) { this.stack.push(node); node = node.left; } }
  next() { const n = this.stack.pop(); this.pushLeft(n.right); return n.val; }
  hasNext() { return this.stack.length > 0; }
}