Solve LeetCode 173: Binary Search Tree Iterator in Python with a lazy inorder stack approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.
This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Binary Tree General |
| Reusable pattern | lazy inorder stack |
| Complexity | O(1) amortized next time and O(h) space |
What the problem is testing
Push the left spine initially and after each pop push the left spine of its right child.
Algorithm
- Push the left spine initially and after each pop push the left spine of its right child.
- Maintain this invariant: The stack top is the smallest not-yet-returned BST node.
- Continue until every input item or reachable state has been resolved, then return the accumulated result.
Python solution
LeetCode provides the list, tree, or graph node definition used by the method.
from collections import Counter, defaultdict, deque, OrderedDict
import random
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)Why this is correct
The proof follows the maintained state: The stack top is the smallest not-yet-returned BST node. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.
Complexity
O(1) amortized next time and O(h) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.
Edge cases
A right subtree can add several nodes, but each node is pushed and popped once.
Tested reference code
This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 124. Binary Tree Maximum Path Sum · Next: 222. Count Complete Tree Nodes