Sub topic 12
Simulating Recursion with an Explicit Stack
This chapter assumes you know how the call stack stores one frame per active call, and how a tail-recursive function becomes a loop. Here we handle the harder case: recursion that is not a tail call, such as a function that makes two recursive calls.
Why the tail-call trick is not enough
A tail-recursive function has nothing left to do after its recursive call returns, so its parameters can simply become loop variables. A tree traversal is different. After visiting the left subtree, the function still has to visit the right subtree. That pending work lives in the call stack frame.
To remove the recursion, you must store that pending work yourself. A Python list works as a stack: append pushes an item, and pop removes the most recently pushed item. The list does the job the call stack did before.
The working model
The conversion follows a fixed pattern:
- Push the starting input onto the stack.
- While the stack is not empty, pop one item.
- Do the work the recursive function did before its recursive calls.
- Push each "recursive call" as a new item, in reverse of the order you want them processed.
Step 4 is the step people get wrong most often. A stack is last-in, first-out, so the item you push last is processed first.
Example: preorder traversal
A preorder traversal records a node, then its left subtree, then its right subtree.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def preorder_recursive(node, out):
if node is None:
return
out.append(node.value)
preorder_recursive(node.left, out)
preorder_recursive(node.right, out)
def preorder_iterative(root):
out = []
stack = [root] if root is not None else []
while stack:
node = stack.pop()
out.append(node.value)
if node.right is not None:
stack.append(node.right)
if node.left is not None:
stack.append(node.left)
return out
tree = Node(1, Node(2, Node(4)), Node(3))
result = []
preorder_recursive(tree, result)
print(result) # [1, 2, 4, 3]
print(preorder_iterative(tree)) # [1, 2, 4, 3]The code pushes the right child before the left child, so the left child sits on top of the stack and is popped next. The None checks take the place of the recursive base case: the code never pushes an empty subtree.
What you gain and what you keep
| Aspect | Recursive version | Explicit-stack version |
|---|---|---|
| Where pending work is stored | Call stack frames | A list on the heap |
| Depth limit | About 1000 frames in CPython by default | Limited by available memory |
| Extra space | O(h) frames, h = tree height | O(h) list entries for preorder |
| Readability | Closer to the definition | More bookkeeping |
The amount of memory used stays about the same. What changes is where it lives. Heap memory is much larger than the call stack, and running out of it does not raise RecursionError.
Common errors
- Pushing children in the order you want them processed, which reverses the traversal.
- Pushing
Noneand then reading.valuefrom it. - Using
pop(0)instead ofpop(). That turns the stack into a queue, so you get a breadth-first traversal instead.
Exercise
In preorder_iterative, you swap the two if blocks so the left child is pushed before the right child. What does the function return for the example tree, and why?
Show answer
It returns [1, 3, 2, 4]. The left child is pushed first and the right child last, so the right child is on top of the stack and gets popped first. The result is a mirrored preorder that visits right subtrees before left ones.
Exercise
Write an iterative function that returns the sum of all values in the tree, using an explicit stack.
Show answer
def tree_sum(root): total = 0 stack = [root] if root is not None else [] while stack: node = stack.pop() total += node.value if node.left is not None: stack.append(node.left) if node.right is not None: stack.append(node.right) return total For the example tree it returns 10. The push order does not matter here because addition gives the same total in any order.