Learn / Binary search trees

BST iterator

A BST iterator returns values in sorted order one at a time. Keep a stack with the path of nodes still to visit: push the far-left chain of the root; next() pops a node and pushes the far-left chain of its right child. Each call is O(1) on average with O(h) memory. Two such walks side by side merge two BSTs.

How to recognise it

  • Values of a BST are needed one at a time, in order.
  • Merging two BSTs, or walking one in both directions.
  • Turning a BST into a sorted list.

The stack is a paused inorder walk

init(root): pushLeft(root)
next():     n = pop; pushLeft(n.right); return n.val
hasNext():  stack is not empty
pushLeft(n): while n: push n; n = n.left

The rule that makes a BST, and how it compares with a heap, is on the Structures page.

Uses

ProblemHow
merge two BSTstwo iterators; take the smaller top each time
flatten to a sorted listinorder; hang each node on the previous one's right
two sum in a BSTone forward and one backward iterator, like two pointers

Common mistakes

  • Pushing the whole tree at the start, which uses O(n) memory.
  • Forgetting to push the right child's left chain after popping.

Problems

0 of 3 solved

Check yourself

After the constructor of the iterator for [7, 3, 15, null, null, 9, 20], what is on the stack?

Why is next() O(1) on average?

How do you merge two BSTs into a sorted list in O(m + n)?