Depth-first traversals: preorder, inorder, postorder
🌍 In real life. A book's table of contents lists a chapter's title first and then its sections, each section before its own sub-sections. Working out how much space a folder takes is the other way round: you can only add up a folder once you know the size of everything inside it. Both go deep first, all the way down one branch before moving to the next; they just differ in when they deal with the thing on top.
A traversal visits every node of a tree exactly once. Going deep first gives three classic orders, and each one is the right tool for a different job.
The idea in one sentence: a depth-first traversal walks a node's left subtree completely, then its right subtree completely, and visits the node itself either before both (preorder), between them (inorder) or after both (postorder).
Its words:
- traversal: a walk that visits every node once
- visit: do the work for a node, here: add its value to the answer
- preorder: node, left subtree, right subtree (the root comes first)
- inorder: left subtree, node, right subtree (the root is in the middle)
- postorder: left subtree, right subtree, node (the root comes last)
- depth-first search (DFS): going as deep as possible before coming back up
How it works, step by step, for the tree 1 → (2 → 4, 5), (3 → right child 6):
- call the walk on the root
- if the node is
None, there is nothing to do: return - preorder visits the node now; then it walks the left subtree, which repeats steps 2–4 for that smaller tree
- inorder visits the node after the left subtree; then it walks the right subtree, and postorder visits the node only now
The gold ring is the walker. Watch where it is when each number appears, first in preorder:
Now inorder: the walker goes as far left as it can before visiting anything, so the leftmost node, 4, comes first. Left to right on the screen is exactly the inorder order:
And postorder: a node waits until both its subtrees are finished, so the root, 1, comes last, like a folder whose size is known only after everything inside it:
Why it is correct. Each call does three things: walks the left subtree, walks the right subtree, and visits its own node once. Every node has exactly one parent, so it is reached by exactly one call, and the recursion visits every node exactly once, whatever the order. The only difference between the three orders is where the visit line sits. Coming back up is handled for you: when a call returns, Python's call stack (Chapter 42) resumes its caller exactly where it stopped. That is the backing-up the walker does in the animation.
What it costs, by counting. n nodes means n visits and n + 1 calls on None children, so the time is O(n). The memory is the call stack: one frame for each node on the way from the root down to where the walker is. That is at most the height h, so O(h): about log₂ n frames for a bushy tree, but n frames for a chain. Python stops at about 1,000 frames, so a chain of 5,000 nodes needs the loop-and-stack version below. The + in the short versions also copies lists, so for big trees, append to one list instead.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def preorder(node):
if node is None:
return []
return [node.val] + preorder(node.left) + preorder(node.right)
def inorder(node):
if node is None:
return []
return inorder(node.left) + [node.val] + inorder(node.right)
def postorder(node):
if node is None:
return []
return postorder(node.left) + postorder(node.right) + [node.val]
root = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
print(preorder(root))
print(inorder(root))
print(postorder(root))
# preorder with a loop and your own stack: no recursion limit
def preorder_stack(root):
out, stack = [], [root]
while stack:
node = stack.pop()
if node is None:
continue
out.append(node.val)
stack.append(node.right) # pushed first, so it comes out last
stack.append(node.left)
return out
print(preorder_stack(root))Mistakes and edge cases.
- a list as a default argument:
def walk(node, out=[])makes one list when the function is defined, and every call shares it, so the second traversal starts with the first one's values; create the list inside the function - the stack version's push order: a stack gives back the last thing pushed, so push the right child before the left one; the other way round gives node, right, left
- which order is which: look at where the root goes: PRE-order puts it first, IN-order in the middle, POST-order last
- an empty tree: every order of
Noneis[]; the base case handles it - very deep trees: recursion past about 1,000 levels raises
RecursionError; use your own stack
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 inorder(node): if node is None: return [] return inorder(node.left) + [node.val] + inorder(node.right) print(inorder(Node("a", Node("b", None, Node("c")), Node("d"))))What does this print?
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right out = [] def walk(node): if node is None: return walk(node.left) walk(node.right) out.append(node.val) walk(Node(1, Node(2), Node(3, Node(4)))) print(out)To add up how much space each folder takes, you need everything inside a folder before the folder itself. Which order is that?
- Postorder
- Preorder
- Inorder
The second print shows [1, 2] instead of [2]. Which line causes it?
def preorder(node, out=[]): if node is not None: out.append(node.val) preorder(node.left, out) preorder(node.right, out) return out print(preorder(Node(1))) print(preorder(Node(2)))A recursive traversal of a chain of n nodes, each with one child: how many frames does the call stack hold at its deepest?
- About n: one for each level, O(h) with h = n
- About log₂ n
- Just 1
Coding tasks
Write
inorder(root): the values in inorder (left subtree, node, right subtree) as a list.This
postorder(root)gives the values in preorder. Fix it so it gives postorder: left subtree, right subtree, then the node.Write
outline(root)for a tree of folders: a list of lines in preorder, each the node's value (as a string) after two spaces for every level of depth. A folder comes before what is inside it, like a table of contents.