SDE & MLE Prep

173. Binary Search Tree Iterator

Problem

Design BSTIterator(root), which walks a BST in sorted (in-order) order: next() returns the next smallest value and hasNext() says whether any remain.

Example: [7,3,15,null,null,9,20] → next() returns 3, 7, 9, 15, 20

Constraints: follow-up: O(1) amortised per call using O(h) memory.

Controlled in-order traversal: stack holds the path of left children. next() pops, then pushes the left spine of its right child. Amortized O(1), O(h) memory.

Complexity: O(1) amortized per call, O(h) space.

class BSTIterator:
    def __init__(self, root: Optional[TreeNode]):
        self.st = []
        self._push_left(root)

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

    def next(self) -> int:
        node = self.st.pop()
        self._push_left(node.right)
        return node.val

    def hasNext(self) -> bool:
        return bool(self.st)