Sub topic 18
Rewriting Recursion with an Explicit Stack
This chapter assumes you know how the call stack holds one frame per active call, why CPython raises RecursionError past its depth limit, and how the recursive Node tree and height function from earlier chapters work. Here you will learn how to remove the recursion from a function by managing the pending work yourself.
Why Convert at All
A recursive call stores its state (local variables and where to resume) in a stack frame that the interpreter manages. CPython caps the number of these frames, which is often 1000 by default. A tree with 100,000 levels breaks the recursive version, even though the computation itself is simple.
An explicit stack is an ordinary Python list that you push work onto and pop work from. It lives on the heap, so its size is limited by memory rather than by the recursion limit. The trade is that you now write down by hand the bookkeeping that the interpreter used to do for you.
The Core Recipe
Each item on the explicit stack stands for "a call that has not run yet." The loop repeats one step: pop an item, do that call's work, and push items for any calls it would have made.
Here is a tree sum written this way. The Node class is repeated so the block runs on its own.
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
tree = Node(1, Node(2, Node(4)), Node(3))
print(tree_sum(tree)) # 10The code pushes the right child before the left child on purpose. A stack is last-in, first-out, so the child pushed last gets popped first. Pushing right then left means the left subtree is processed first, which matches the preorder visit order of the recursive version. Addition does not care about order, but many traversals do.
Proving the Depth Advantage
The next block builds a tree that is a chain of 100,000 left children. It compares a recursive sum with the iterative one.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def tree_sum_recursive(node):
if node is None:
return 0
return node.value + tree_sum_recursive(node.left) + tree_sum_recursive(node.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
root = None
for v in range(100000):
root = Node(v, left=root)
try:
tree_sum_recursive(root)
except RecursionError:
print("recursive version: RecursionError")
print(tree_sum(root)) # 4999950000The recursive version fails and the loop finishes. The tree is built with a loop as well, because a recursive builder would hit the same limit.
Carrying State That Frames Used to Hold
In a recursive call, parameters such as "current depth" travel with the frame. With an explicit stack, you push that state alongside the node as a tuple.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def height_iterative(root):
if root is None:
return 0
best = 0
stack = [(root, 1)]
while stack:
node, depth = stack.pop()
best = max(best, depth)
if node.right is not None:
stack.append((node.right, depth + 1))
if node.left is not None:
stack.append((node.left, depth + 1))
return best
tree = Node(1, Node(2, Node(4)), Node(3))
print(height_iterative(tree)) # 3The recursive height computed its answer from the children's return values. This version takes a different route: it passes depth downward and records the maximum seen. Rewriting a "combine results on the way up" function as "pass information on the way down" is often the simplest conversion.
When Work Must Happen After the Children
Some computations must run after both subtrees finish. Postorder traversal is one example, and so is evaluating an expression tree. The recursive code does this by running statements after the recursive calls return. A plain pop-and-process loop has no "after."
You can get the "after" back by pushing each node twice. The first time, a flag marks it as "expand children." The second time, the flag marks it as "children done, now process."
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def postorder(root):
out = []
stack = [(root, False)] if root is not None else []
while stack:
node, children_done = stack.pop()
if children_done:
out.append(node.value)
else:
stack.append((node, True))
if node.right is not None:
stack.append((node.right, False))
if node.left is not None:
stack.append((node.left, False))
return out
tree = Node(1, Node(2, Node(4)), Node(3))
print(postorder(tree)) # [4, 2, 3, 1]The flag acts as a tiny return address. It records which part of the "function body" should run when the item is popped again. A fully general conversion of any recursive function works the same way: each stack entry holds the arguments, the local variables, and a step number saying where to resume.
Choosing Between the Forms
| Concern | Recursive | Explicit stack |
|---|---|---|
| Maximum depth | Limited by recursion limit (often 1000) | Limited by memory |
| Readability | Usually mirrors the problem definition | More bookkeeping, easier to get order wrong |
| Post-processing after children | Natural: code after the call | Needs flags or step numbers |
| Changing traversal order | Rewrite the calls | Swap stack for queue or change push order |
| Speed in CPython | Function-call overhead per node | Usually similar or slightly faster |
Keep the recursive form when the depth is bounded and small. A balanced tree with a million nodes is only about 20 levels deep. Convert when the input can be deep or degenerate: linked-list-shaped trees, long chains in a graph, or input controlled by untrusted users. Raising the limit with sys.setrecursionlimit is a weaker fix, because it can crash the interpreter itself if the C stack runs out.
Exercise
In tree_sum, what happens to the visit order if you push the left child before the right child?
Show answer
The right subtree is popped and processed first, because the stack returns the most recently pushed item. The sum is unchanged, but a traversal that records values would list the right side before the left (for the sample tree: 1, 3, 2, 4 instead of 1, 2, 4, 3).
Exercise
For the 100,000-node left-chain tree, what is the largest size the explicit stack reaches in tree_sum, and why?
Show answer
One. Each pop removes the only node and pushes at most its single left child, so the stack never holds more than one item. Stack size depends on the tree's shape. For a wide tree it grows with the number of pending siblings.
Exercise
Write an iterative function that sums all integers in an arbitrarily nested list such as [1, [2, [3, 4]], 5] without recursion.
Show answer
Start with stack = [data] and total = 0. While the stack is non-empty, pop an item. If it is a list, extend the stack with its elements. Otherwise add it to total. Return total. For the example, the result is 15.