Post-order Traversal
In a post-order traversal you visit a node after both of its subtrees:
- Traverse the left subtree in post-order.
- Traverse the right subtree in post-order.
- Visit the node itself.
Children are always handled before their parent, so the root is visited last. Here is the same tree again:
40
/ \
22 61
/ \ / \
15 30 52 70
/
27Recursive implementation
class Node:
def __init__(self, value, left=None, right=None):
self.value, self.left, self.right = value, left, right
root = Node(40,
Node(22, Node(15), Node(30, Node(27))),
Node(61, Node(52), Node(70)))
def postorder(node, out):
if node is None:
return
postorder(node.left, out)
postorder(node.right, out)
out.append(node.value) # the node comes last
order = []
postorder(root, order)
print(order)[15, 27, 30, 22, 52, 70, 61, 40]
Comparing the three orders
The three depth-first traversals differ only in where the "visit" line goes. All three walk the tree along the same path; they just record the node at a different moment:
class Node:
def __init__(self, value, left=None, right=None):
self.value, self.left, self.right = value, left, right
root = Node(40, Node(22, Node(15), Node(30, Node(27))), Node(61, Node(52), Node(70)))
def walk(node, when, out):
if node is None:
return
if when == "pre": out.append(node.value)
walk(node.left, when, out)
if when == "in": out.append(node.value)
walk(node.right, when, out)
if when == "post": out.append(node.value)
for when in ("pre", "in", "post"):
out = []
walk(root, when, out)
print(f"{when + '-order:':<11}", out)pre-order: [40, 22, 15, 30, 27, 61, 52, 70]
in-order: [15, 22, 27, 30, 40, 52, 61, 70]
post-order: [15, 27, 30, 22, 52, 70, 61, 40]
Why visit children first?
Post-order is the right choice whenever a node's answer depends on its children's answers.
Computing folder sizes. A folder's size is its own files plus the sizes of its subfolders, so the subfolders must be measured first:
class Folder:
def __init__(self, name, files=0, subfolders=()):
self.name, self.files, self.subfolders = name, files, list(subfolders)
def total_size(folder, depth=0):
size = folder.files + sum(total_size(sub, depth + 1) for sub in folder.subfolders)
print(" " * depth + f"{folder.name}: {size} KB") # printed after its children
return size
home = Folder("home", 4, [
Folder("photos", 820, [Folder("2025", 1300)]),
Folder("docs", 96),
])
total_size(home) 2025: 1300 KB
photos: 2120 KB
docs: 96 KB
home: 2220 KB
Notice how each folder line is printed after the lines of its subfolders.
Evaluating an expression tree. An operator can only be applied once both operands are known. Post-order gives postfix notation, which the stack evaluator from the Stacks lesson computes directly:
class Node:
def __init__(self, value, left=None, right=None):
self.value, self.left, self.right = value, left, right
expr = Node("*", Node("+", Node(3), Node(4)), Node("-", Node(10), Node(6)))
def postfix(node):
if node.left is None:
return [str(node.value)]
return postfix(node.left) + postfix(node.right) + [node.value]
def evaluate(node):
if node.left is None:
return node.value
a, b = evaluate(node.left), evaluate(node.right) # children first
return {"+": a + b, "-": a - b, "*": a * b}[node.value]
print(" ".join(postfix(expr)))
print(evaluate(expr))3 4 + 10 6 - *
28
Deleting a tree. In languages with manual memory management, you must free the children before the parent; otherwise you lose the pointers to them.
Summary of the traversals
| Traversal | Order | Typical use |
|---|---|---|
| Pre-order | node, left, right | copying/serialising, printing hierarchies, prefix notation |
| In-order | left, node, right | sorted output of a BST, infix notation |
| Post-order | left, right, node | sizes and heights, evaluating expressions, deleting |
| Level-order | level by level (queue) | shortest paths, printing by depth |
All of them take O(n) time and O(h) extra memory for a tree of height h.
Test yourself
Which node is always visited last in a post-order traversal?
- The leftmost leaf
- The root
- The rightmost leaf
- The deepest node
What is the post-order traversal of root 1 with left child 2 and right child 3, where 2 has a left child 4?
- 4 2 3 1
- 4 2 1 3
- 1 2 4 3
- 3 4 2 1
Which traversal fits computing the total size of every folder in a file tree?
- Pre-order
- In-order
- Post-order
- None of them