LeetCode 173: Binary Search Tree Iterator — Python Solution

LeetCode 173: Binary Search Tree Iterator is a Medium binary tree general problem. This Python walkthrough develops a lazy inorder stack solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicBinary Tree General
Reusable patternlazy inorder stack
ComplexityO(1) amortized next time and O(h) space

Recognizing the pattern

Tree recursion works when the return value has one precise meaning for every subtree; the parent can then combine child results locally.

For this problem specifically, push the left spine initially and after each pop push the left spine of its right child. The invariant worth writing beside the code is: The stack top is the smallest not-yet-returned BST node.

Step-by-step algorithm

  1. Identify the input state consumed by _push_left(node) and initialize the data required by the lazy inorder stack pattern.
  2. Push the left spine initially and after each pop push the left spine of its right child.
  3. After each update, verify the page’s central invariant: The stack top is the smallest not-yet-returned BST node.
  4. Finish only after the boundary behavior is covered: A right subtree can add several nodes, but each node is pushed and popped once.

Python solution

LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.

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 bool(self.stack)

Reading the implementation

The main entry point is _push_left(node). The named working state includes node; those variables make the lazy inorder stack state visible instead of hiding it in incidental control flow.

The entry point is recursive: each call reduces the remaining tree, graph, or search state before combining the returned information. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, push the left spine initially and after each pop push the left spine of its right child.

Correctness argument

Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.

Inductive step. Push the left spine initially and after each pop push the left spine of its right child. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so the stack top is the smallest not-yet-returned BST node.

Conclusion. Every recursive call reduces the remaining state. The base cases terminate, and induction carries the invariant back to the original input, establishing the returned answer.

Complexity and trade-offs

O(1) amortized next time and O(h) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

An explicit stack avoids recursion-depth limits, but it must carry the same state that recursive call frames provide automatically. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

bst=tree([7,3,15,None,None,9,20]); it=BSTIterator(bst); values=[]

Common mistakes and edge cases

  • Problem-specific boundary: A right subtree can add several nodes, but each node is pushed and popped once.
  • Pattern-level pitfall: Write the empty-subtree result first and keep returned subtree information separate from any global answer updated at a node.
  • Invariant check: after every update, confirm that the stack top is the smallest not-yet-returned BST node.

Interview review checklist

  • Explain why lazy inorder stack matches the structure of this input.
  • State the invariant in one sentence before tracing code: The stack top is the smallest not-yet-returned BST node.
  • Derive O(1) amortized next time and O(h) space from how many times each element or state is visited.
  • Test the boundary explicitly: A right subtree can add several nodes, but each node is pushed and popped once.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 124. Binary Tree Maximum Path Sum · Next: 222. Count Complete Tree Nodes