Binary Search Tree Iterator
MediumTop Interview 150 TreesProblem
Design an iterator over a binary search tree that hands out its values from smallest to largest.
BSTIterator(root)creates the iterator from the tree's root.next()returns the smallest value not returned yet.hasNext()returnstrueif there is still a value to return.
Every next() call is valid: it is only made when a value is left. The tree is given in level order,
with null for a missing child. Aim for next() and hasNext() to be O(1) on average,
using memory proportional to the tree's height.
Constraints
- 1 ≤ number of nodes ≤ 100000
- 0 ≤ Node.val ≤ 1000000
- At most 100000 calls to next and hasNext
Examples: pick one to animate
Solutions
Time: A single next() may push a whole left edge, but each node is pushed once and popped once over all calls, so the average cost per call is constant. hasNext is a single check.
Space: The stack holds one root-to-node path at most, so h nodes. That is log n for a balanced tree and n for a chain.
An in-order walk visits values smallest first, so run it lazily. Keep a stack holding the path of nodes whose turn has not come: always push a node and then walk to its left child. The top is the smallest unreturned value. next() pops it, then stacks the left edge of its right child, which holds the values just above it. hasNext() only asks whether the stack is empty.