Sub topic 10
Traversing without recursion using an explicit stack
This chapter assumes you know recursion and the call stack, how a stack works (push and pop), and the Node class and root tree from earlier chapters.
Why remove the recursion
A recursive traversal keeps its pending work on the call stack. Python limits that stack to about 1000 frames by default. A degenerate tree, where every node has only one child, can have 5000 nodes in a chain. Recursing on it raises RecursionError. An explicit stack is a Python list that lives on the heap, so its size is limited only by memory.
The idea is to do by hand what the interpreter does for you. Keep a stack of nodes whose work is not finished, and pop one when you are ready to continue.
Preorder
Preorder visits a node, then its left subtree, then its right subtree. Push the root, then repeat: pop a node, visit it, and push its children.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
root = Node(1, Node(2, Node(4), Node(5)), Node(3))
def preorder_iterative(root):
if root is None:
return []
result = []
stack = [root]
while stack:
node = stack.pop()
result.append(node.value)
if node.right is not None:
stack.append(node.right)
if node.left is not None:
stack.append(node.left)
return result
print(preorder_iterative(root)) # [1, 2, 4, 5, 3]Push the right child first. A stack pops the last item pushed, so the left child comes off first.
Inorder
Inorder is harder, because a node must wait until its whole left subtree is done. The loop first walks down the left edge and pushes every node on the way. It then pops a node, visits it, and moves to that node's right child.
def inorder_iterative(root):
result = []
stack = []
current = root
while current is not None or stack:
while current is not None:
stack.append(current)
current = current.left
current = stack.pop()
result.append(current.value)
current = current.right
return result
print(inorder_iterative(root)) # [4, 2, 5, 1, 3]Postorder
Postorder is the trickiest, because a node is visited only after both subtrees. A short trick avoids the bookkeeping. Run preorder with the children pushed in the opposite order (node, right, left), then reverse the result. That gives left, right, node.
Cost and common errors
Time is O(n), because each node is pushed and popped once. Extra space is O(h), where h is the tree height. This is the same as the recursion depth, but the stack no longer hits the interpreter's limit.
- Pushing children in the wrong order. In preorder, pushing left before right visits the right subtree first.
- Forgetting
or stackin the inorder loop. The loop then ends as soon ascurrentbecomesNone, and nodes still on the stack are skipped. - Pushing
None. Check each child before pushing it, ornode.valuefails on a missing child.
Exercise
In inorder_iterative, what is the largest size the stack reaches on the tree where every node has only a left child, with n nodes?
Show answer
n. The inner loop pushes every node down the left edge before the first pop, so the stack holds all n nodes. This matches the O(h) space bound, because h = n - 1 for this shape.