Sub topic 18
Rewriting Recursion with an Explicit Stack
This chapter assumes you know how the call stack stores one frame per active call, and that CPython raises RecursionError once the call depth passes its limit (often 1000). It also reuses the Node class from the chapter on trees.
Why convert at all
A recursive tree walk uses one stack frame for each level of the tree. A balanced tree with a million nodes is only about 20 levels deep, so that is fine. A degenerate tree, where every node has only a left child, has a depth equal to its size, and the recursive version crashes. The fix is to keep the pending work in a Python list, which can grow to millions of entries, instead of leaving it to the interpreter's call stack.
The working model
Each recursive call means "handle this node later." With an explicit stack, you push the node onto a list. A loop takes items off the list until it is empty:
- Push the starting item.
- Pop an item and process it.
- Push the smaller subproblems that the recursive version would have called.
- Repeat until the stack is empty.
The code
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def tree_sum(root):
if root is None:
return 0
total = 0
stack = [root]
while stack:
node = stack.pop()
total += node.value
if node.right is not None:
stack.append(node.right)
if node.left is not None:
stack.append(node.left)
return total
# A degenerate tree 100,000 levels deep
root = Node(1)
current = root
for _ in range(99_999):
current.left = Node(1)
current = current.left
print(tree_sum(root)) # 100000The code pushes the right child before the left child, so the left child is popped first. That matches the visiting order of the recursive version. A recursive tree_sum on this tree would raise RecursionError.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Pushing `None` children | `AttributeError` on `node.value` | Check for `None` before pushing, or skip it after popping |
| Using `pop(0)` | Breadth-first order, and each pop costs O(n) | Use `pop()` for stack (LIFO) order |
| Forgetting per-call state | Wrong answers for depth or path problems | Push tuples such as `(node, depth)` |
Exercise
Rewrite height(node) from the trees chapter without recursion, using an explicit stack. Hint: store the depth alongside each node.
Show answer
Push (node, depth) pairs and track the largest depth you see: def height(root): if root is None: return 0 best = 0 stack = [(root, 1)] while stack: node, d = stack.pop() best = max(best, d) if node.left is not None: stack.append((node.left, d + 1)) if node.right is not None: stack.append((node.right, d + 1)) return best For Node(1, Node(2, Node(4)), Node(3)) it returns 3.