Sub topic 12
Simulating Recursion with an Explicit Stack
This chapter assumes you can read a recursive function and name its base case. It also assumes you know that each call pushes a frame onto the call stack, and that you have seen how a tail-recursive function becomes a while loop. The tail-call trick only works when nothing is left to do after the recursive call returns. Most interesting recursion does not fit that shape. A tree traversal makes two recursive calls, and the function still has work to do between and after them. For these cases you need a different technique: keep the pending work in a stack that you manage yourself.
Why Tail-to-Loop Conversion Is Not Enough
In a tail-recursive function, the current frame is no longer needed once the recursive call starts, so its parameters can be overwritten by loop variables. A non-tail call is different. When preorder_recursive(node.left, out) runs, the frame for node must survive, because it still has to call preorder_recursive(node.right, out) afterward. The call stack is what remembers "come back here and do the right subtree next."
If you want to remove the recursion, something else has to remember that pending work. A Python list used as a stack does this. append pushes onto the top and pop removes from the top, and both run in O(1) amortized time.
| Recursive version | Explicit-stack version |
|---|---|
| Call stack managed by the runtime | List managed by your code |
| A stack frame (parameters plus where to resume) | A stack entry (a node, sometimes with a state flag) |
| Making a recursive call | `stack.append(...)` |
| Returning from a call | Finishing the current loop iteration |
| Base case returns immediately | Skip `None` children, or never push them |
| Limited by `sys.getrecursionlimit()` | Limited by heap memory |
Preorder Traversal: The Simple Case
Preorder visits a node, then its left subtree, then its right subtree. Here are the recursive and iterative versions side by side:
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]Preorder converts this simply because the node's own work, out.append(node.value), happens before either child is processed. After that, the frame only has to remember "do left, then right." Pushing both children captures that completely. No frame needs to come back later and do more.
The push order is reversed. A stack is last-in, first-out, so the right child goes in first and the left child sits on top and comes out next. If you push left before right, the code still runs and still visits every node, but it produces [1, 3, 2, 4]. This is the most common bug in this conversion, and it never raises an error.
When the Frame Has Work Left After Its Children
Postorder visits the left subtree, the right subtree, and then the node. Here the node's own work happens after both children finish, so when you first pop a node you cannot process it yet. You have to put it back and remember that its children have already been scheduled.
The general fix is to store a state flag with each stack entry. The flag plays the role of the "resume point" a real stack frame keeps. In postorder the flag expanded means "this node's children have already been pushed."
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def postorder_iterative(root):
out = []
stack = [(root, False)] if root is not None else []
while stack:
node, expanded = stack.pop()
if expanded:
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_iterative(tree)) # [4, 2, 3, 1]Each node goes onto the stack twice. On the first pop it is unexpanded: the code pushes the node back with True underneath its children. On the second pop it is expanded, and the code records it. Because the True entry sits below the children, it only comes back out after both subtrees are done.
You can use the same pattern for any recursive function. If a function has several points where it can resume, store a small integer phase instead of a boolean, such as 0 for "not started", 1 for "left done" and 2 for "both done".
Returning Values Up the Tree
Recursive functions often combine the results of their children, as in return node.value + sum(left) + sum(right). An explicit stack has no return values, so you need a second stack that holds finished results. When a node is processed in its expanded state, its children's results are already sitting on top of the results stack.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def tree_sum_iterative(root):
if root is None:
return 0
results = []
stack = [(root, False)]
while stack:
node, expanded = stack.pop()
if not expanded:
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))
else:
right = results.pop() if node.right is not None else 0
left = results.pop() if node.left is not None else 0
results.append(node.value + left + right)
return results.pop()
tree = Node(1, Node(2, Node(4)), Node(3))
print(tree_sum_iterative(tree)) # 10The left subtree finishes first, so its result goes onto results first. That puts the right subtree's result on top, which is why the code pops right before left. For a sum the order does not matter, but for any operation where order matters, such as building a list or subtracting, getting it backwards gives silently wrong answers.
The Payoff: Depth Limited Only by Memory
The main practical reason to do this conversion in Python is depth. A degenerate tree, where every node has only a left child, is effectively a linked list. If it is 100,000 nodes deep, the recursive version blows past CPython's default limit of about 1000 frames. The iterative version just grows a list.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def build_chain(n):
root = Node(0)
current = root
for i in range(1, n):
current.left = Node(i)
current = current.left
return root
def height_recursive(node):
if node is None:
return 0
return 1 + max(height_recursive(node.left), height_recursive(node.right))
def height_iterative(root):
best = 0
stack = [(root, 1)] if root is not None else []
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
chain = build_chain(100_000)
print(height_iterative(chain)) # 100000
try:
height_recursive(chain)
except RecursionError:
print("RecursionError") # RecursionErrorheight_iterative shows another useful trick. The depth is passed down inside each stack entry, the way a parameter would be passed down. Because the value travels downward, no results stack is needed.
Edge Cases and Gotchas
- Empty input. Guard the first push (
[root] if root is not None else []), or the loop will popNoneand fail on.value. - Graphs, not trees. In depth-first search on a graph with cycles, keep a
visitedset. Marking a node visited when you push it gives a different visit order than marking it when you pop it. Recursive DFS matches the pop-time version: checkvisitedafter popping, and skip the node if it is already there. - Mutation during traversal. The explicit stack holds references to nodes. If the tree changes mid-traversal, the stack can hold stale nodes. The same is true of recursion, but it is easier to forget here.
- Readability cost. The postorder and sum versions are harder to read than their three-line recursive versions. Convert only when depth or the runtime's limits make you.
Exercise
Write an iterative inorder traversal (left subtree, node, right subtree) using an explicit stack and no state flags. For Node(1, Node(2, Node(4)), Node(3)) it should return [4, 2, 1, 3].
Show answer
Walk left as far as you can, pushing each node. Then pop a node, record it, and move to its right child:
def inorder_iterative(root):
out, stack, node = [], [], root
while stack or node is not None:
while node is not None:
stack.append(node)
node = node.left
node = stack.pop()
out.append(node.value)
node = node.right
return out
The node variable stands in for "the call about to start", and the stack holds frames waiting for their left subtree to finish.
Exercise
In postorder_iterative, a student pushes (node, True) after pushing the two children instead of before. What output does the function give for Node(1, Node(2, Node(4)), Node(3)), and why?
Show answer
It gives [1, 2, 4, 3]. The (node, True) entry now sits on top of the stack, so it is popped and recorded right away, before either child. Each node is recorded before its subtrees, which is preorder. The expanded entry must be pushed first so that it lies underneath its children.
Exercise
treesumiterative uses a second stack for results, but height_iterative does not. What property of the computation decides whether you need one?
Show answer
It depends on which way information flows. heightiterative passes depth downward from parent to child, so the value can travel inside each stack entry. treesum needs values flowing upward, because a parent's result depends on its children's results. Those must be stored somewhere until the parent is processed in its expanded state.