Walking a tree with your own stack
🌍 In real life. Exploring a cave with many forks, you can't keep everything in your head, so you leave a chalk mark at each fork you will come back to, and the newest mark is the first one you return to. That pile of marks is a stack.
Recursion keeps such a pile for you: Python's call stack (Lesson 42.1). But that stack is small, about 1,000 calls by default, and a tree 5,000 levels deep (a long chain of nodes) stops with RecursionError. Keeping the stack yourself, in an ordinary list, walks any tree, however deep, and is a classic interview question too (LeetCode 94, 144, 145).
The idea in one sentence: a recursive traversal can be rewritten with a list used as a stack, which holds the nodes still waiting to be finished, so the order stays the same and the depth limit disappears.
Its words:
- explicit stack: a list you push to and pop from yourself, instead of the call stack
- iterative: written with loops instead of recursion
- leftmost path: the nodes you meet going left from a node until there is no left child
Step by step, inorder with a stack:
- From the current node, go left as far as you can, pushing every node you pass: they are waiting for their turn.
- Pop one: it is the leftmost node not yet visited. Visit it.
- Move to its right child, and repeat from step 1.
- Stop when the stack is empty and there is no current node.
The recursive inorder, for comparison:
And the same walk with a stack you keep yourself. Here the tree is a dict from each value to its two children, so the stack can show plain numbers:
Preorder and postorder with a stack.
- Preorder is the easiest: push the root; then pop a node, visit it, and push its right child before its left, so the left one is popped, and visited, first.
- Postorder has a neat trick: the same loop with the pushes swapped visits node, right, left; reversed at the end, that is left, right, node.
Why it works. In inorder, the stack always holds exactly the nodes whose left subtree is being walked and who haven't been visited yet: the same frames the recursive version would have open. Popping one means its left side is finished, which is when recursion would visit it.
What it costs, by counting. Every node is pushed once and popped once: O(n) time, the same as recursion. The stack holds at most h nodes for inorder (h is the height), at most about n for a wide tree in preorder, and n for the reversed postorder list. The difference is where that memory lives: in a list, which can grow into millions, rather than in the call stack, which can't.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder(root):
out, stack, node = [], [], root
while stack or node:
while node: # go left as far as you can
stack.append(node)
node = node.left
node = stack.pop() # the leftmost node not yet visited
out.append(node.val)
node = node.right # then its right subtree
return out
def preorder(root):
if root is None:
return []
out, stack = [], [root]
while stack:
node = stack.pop()
out.append(node.val)
if node.right: # pushed first, so popped after the left
stack.append(node.right)
if node.left:
stack.append(node.left)
return out
def postorder(root):
if root is None:
return []
out, stack = [], [root]
while stack: # node, right, left ...
node = stack.pop()
out.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return out[::-1] # ... reversed is left, right, node
root = Node(4, Node(2, Node(1), Node(3)), Node(6))
print(inorder(root), preorder(root), postorder(root))
chain = None
for value in range(1000): # 1,000 levels: deeper than recursion allows
chain = Node(value, chain)
print(len(inorder(chain)), inorder(chain)[:3])Mistakes and edge cases.
- Pushing left before right in preorder. The right child is then popped first, and the order comes out node, right, left.
- Forgetting
node = node.rightin inorder. Every right subtree is skipped. while node:with zeros. That test is about the node object, which is fine; but if you store values on the stack, a value 0 is falsy, so writeis not None.- Raising the recursion limit instead.
sys.setrecursionlimit(10**6)can crash Python itself when the real C stack runs out; an explicit stack is the safe fix. - An empty tree. Preorder and postorder must return
[]forNonebefore pushing anything.
Quiz
What does this print?
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def postorder(root): if root is None: return [] out, stack = [], [root] while stack: # node, right, left ... node = stack.pop() out.append(node.val) if node.left: stack.append(node.left) if node.right: stack.append(node.right) return out[::-1] # ... reversed is left, right, node print(postorder(Node(1, Node(2), Node(3, Node(4)))))Why walk a tree with your own stack instead of recursion?
- A very deep tree passes Python's recursion limit; a list can grow much bigger
- It visits fewer nodes
- It changes the order of the walk
In the stack inorder, what does popping a node mean?
- Its left subtree is finished, so it is its turn to be visited
- Its whole subtree is finished
- It is a leaf
preorder(Node(1, Node(2, Node(4)), Node(3))) should be [1, 2, 4, 3], but gives [1, 3, 2, 4]. Which line is wrong?
def preorder(root): if root is None: return [] out, stack = [], [root] while stack: node = stack.pop() out.append(node.val) if node.left: stack.append(node.left) if node.right: stack.append(node.right) return out
Coding tasks
Write
inorder(root)without recursion: the values in inorder, using a list as a stack. It must work on a chain of 1,000 nodes.Write
postorder(root)without recursion. (Hint: a node, right, left walk, reversed.)