Binary Search Tree Iterator Problem
Description
LeetCode Problem 173.
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
- BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
- boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
- int next() Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.
You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.
Example 1:
Input
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
Output
[null, 3, 7, true, 9, true, 15, true, 20, false]
Explanation
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next(); // return 3
bSTIterator.next(); // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 20
bSTIterator.hasNext(); // return False
Constraints:
- The number of nodes in the tree is in the range [1, 10^5].
- 0 <= Node.val <= 10^6
- At most 10^5 calls will be made to hasNext, and next.
Solution
Approach: Controlled In-Order Traversal with a Stack
The simplest idea is to run a full in-order traversal in the constructor and store all values in a list. That works, but it uses O(n) memory up front. Instead, we can pause an iterative in-order traversal between calls, keeping only a stack of nodes.
The stack holds the path from the root down to the next smallest node that has not been returned yet, with that node on top. Every node on the stack is still waiting for its value to be returned.
- Constructor: push
root, then its left child, then that node's left child, and so on. The last node pushed is the smallest value in the tree. - next(): pop the top node; that is the answer. Its in-order successor is either the smallest node of its right subtree, or (if it has no right subtree) the next node already on the stack. So push the left path of
node.rightbefore returningnode.val. - hasNext(): there is a next value exactly when the stack is not empty.
The detail that is easy to miss is pushing the right subtree's whole left path, not just node.right itself: the smallest value of that subtree is at the bottom of its leftmost path.
Complexity: hasNext is O(1). next is O(1) amortized: across all calls each node is pushed and popped exactly once, though a single call can push up to h nodes. The stack uses O(h) space, where h is the height of the tree.
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.stack = [] # the path to the next smallest node, smallest on top
self._push_left_path(root)
def next(self) -> int:
node = self.stack.pop()
# The next values after node are in its right subtree, smallest first.
self._push_left_path(node.right)
return node.val
def hasNext(self) -> bool:
return len(self.stack) > 0
def _push_left_path(self, node: Optional[TreeNode]) -> None:
while node:
self.stack.append(node)
node = node.left