Walk a BST in sorted order one call at a time. Keep a stack of the left spine; each next() pops a node and pushes its right child's left spine.
▼The problem
LeetCode 173 (Medium). Implement BSTIterator(root) over a binary search tree: next() returns the next smallest value (in-order), hasNext() says whether any values are left.
LeetCode's example: tree [7,3,15,null,null,9,20], calls next, next, hasNext, next, hasNext, next, hasNext, next, hasNext → [null,3,7,true,9,true,15,true,20,false] (the first entry is the constructor). The walkthrough runs it.
The naive way shown: walk the whole tree in order in the constructor and copy every value into a list; next() just reads the list (O(1)), but the list holds all n values even if only one is ever asked for (O(n) memory). The solution shown: an in-order walk paused between calls, with an explicit stack. A helper pushes a node and its left children (the left spine); the constructor calls it on the root; next() pops the top (the smallest value not yet returned), calls the helper on its right child and returns the value; hasNext() is "the stack is not empty". Every node is pushed once and popped once, so next() is amortised O(1) (one call can push a whole spine, O(h) at worst); the stack holds part of one root-to-node path, so the memory is O(h). The exact code on screen (CODE in src/scenes/S5.jsx):
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 len(self.stack) > 0Checked in Python against the sorted values on 20,000 random BSTs (0–25 nodes, built by random insertion): every next() returns the next sorted value, hasNext() is right before every call, and the stack never grows past the tree's height. Every value on screen is computed in code: runIter() in src/deli.jsx runs the same algorithm and records every push, pop and hasNext; the module re-checks it on 400 random BSTs when it loads, and every scene asserts the values it shows (event signatures such as +7 +3 -3 -7 +15 +9 ?T -9 ?T -15 +20 ?T -20 ?F, the cost scene's pushes per call 2,0,2,0,1,0, h = 3, at most 2 on the stack). src/gen_score.py re-runs it (run_iter) and asserts the same signatures for its sound cues.
The 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 len(self.stack) > 0Transcript
Binary Search Tree Iterator. Build an iterator over a search tree. Next returns the next smallest value, and has next says whether any values are left.
Take seven at the root, with three on its left, and fifteen on its right over nine and twenty. In order, that's three, seven, nine, fifteen, twenty. So next gives three, then seven. Has next says true. Keep going until twenty is gone, and has next says false.
The easy way: walk the whole tree up front, and copy every value into a list. Then next just reads the list. That's quick, but the list holds all n values, even if you only ever ask for one.
The better idea: an in-order walk, paused between calls. Keep a stack of nodes still waiting. First, push the left spine: the root, its left child, and on down. The top of the stack is always the smallest value not yet returned. To serve it, pop it. Then push its right child's left spine.
In code, a helper pushes a node and its left children, all the way down. The constructor calls it on the root. Next pops the top, calls the helper on its right child, and returns the value. Has next checks that the stack isn't empty.
Now the example. Push seven, then three. Next pops three. It has no right child, so nothing goes on. Next pops seven, and pushes fifteen, then nine. Has next: true. Pop nine. True again, so pop fifteen, which pushes twenty. True, pop twenty. The stack is empty, so has next is false.
Each node is pushed once and popped once. So next takes constant time on average, even when one call pushes a whole spine. And the stack only holds part of one path down the tree: order h space, not n.
Push the left spine, pop the smallest, push the right child's spine. That's Binary Search Tree Iterator.