Sub topic 2
Children Before Parents: Post-order and Iterative DFS
Every tree DP in this tutorial has the same requirement: a node's value can only be computed after the values of all its children are known. This chapter covers how to produce an order that guarantees this, why the textbook recursive approach fails on real inputs, and how to build the order with an explicit stack so it works on trees of any shape.
This chapter assumes you are comfortable with adjacency lists, depth-first search, and Big-O notation. It also assumes you have read the previous chapter, which explained what it means to root a tree and introduced the parent array.
Why the order matters
A tree DP computes one value (or a small tuple of values) per node, and that value depends on the children's values. Subtree size is the simplest case: size[u] = 1 + sum(size[c] for c in children(u)). If you compute size[u] before some child c is finished, you add a stale value and the answer is wrong without any error being raised.
So any order where every node comes after all of its descendants will work. Post-order is the standard example, but it is not the only one. Any order with the "children before parents" property is enough:
| Order | Children before parents? | Notes |
|---|---|---|
| Recursive post-order | Yes | Natural to write, but limited by recursion depth |
| Iterative pre-order, reversed | Yes | The approach used in this tutorial |
| Explicit iterative post-order | Yes | Needs a "visited" flag on stack entries |
| BFS order, reversed | Yes | Deeper levels come first |
| Forward pre-order or BFS order | No | Parents come first, which suits top-down passes |
The last row matters too. Rerooting, covered in a later chapter, needs a top-down pass where each parent is finished before its children. The forward pre-order gives you that for free. One traversal therefore gives you both directions: walk it backwards for bottom-up DP and forwards for top-down propagation.
The recursive version and where it breaks
Here is the version most people write first:
def subtree_sizes_recursive(n, edges, root=0):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
size = [1] * n
def dfs(u, p):
for v in adj[u]:
if v != p:
dfs(v, u)
size[u] += size[v]
dfs(root, -1)
return size
if __name__ == "__main__":
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5)]
print(subtree_sizes_recursive(6, edges)) # [6, 3, 2, 1, 1, 1]
n = 5000
path = [(i, i + 1) for i in range(n - 1)]
try:
subtree_sizes_recursive(n, path)
except RecursionError as e:
print("RecursionError:", e)The code is correct, and it fails anyway. On a path of 5000 nodes the recursion goes 5000 calls deep. CPython's default recursion limit is 1000, so the call raises RecursionError. Test data for tree problems almost always includes a long path, or a "caterpillar" (a long path with short branches hanging off it), because those shapes have depth close to n.
The same issue appears in other languages in different forms. C++ and Java have fixed thread stack sizes, usually 1 to 8 MB, and a recursion depth of 10^6 can overflow them. The iterative pattern below carries over to any language.
Iterative DFS that records a pre-order
The function below, shared by every later chapter, builds the parent array, a traversal order, and subtree sizes using only an explicit stack:
def root_tree(n, edges, root=0):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent = [-1] * n
seen = [False] * n
seen[root] = True
order = []
stack = [root]
while stack:
u = stack.pop()
order.append(u)
for v in adj[u]:
if not seen[v]:
seen[v] = True
parent[v] = u
stack.append(v)
size = [1] * n
for u in reversed(order):
if parent[u] != -1:
size[parent[u]] += size[u]
return parent, order, size
if __name__ == "__main__":
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5)]
parent, order, size = root_tree(6, edges)
print("parent:", parent) # [-1, 0, 0, 1, 1, 2]
print("order: ", order) # [0, 2, 5, 1, 4, 3]
print("size: ", size) # [6, 3, 2, 1, 1, 1]
n = 200000
path = [(i, i + 1) for i in range(n - 1)]
_, _, big = root_tree(n, path)
print(big[0]) # 200000, no recursion involvedWhy parents always precede children
A node v is pushed onto the stack only while its parent u is being processed, and u has already been appended to order at that point. v is appended later, when it is popped. So parent[v] always appears in order before v. That makes order a topological order from root to leaves, and reversed(order) puts every node after all of its descendants.
The seen array ensures each node is pushed exactly once. Nodes are marked when they are pushed, not when they are popped, so no node can sit on the stack twice. Each node is pushed and popped once and each adjacency entry is scanned once, so the traversal runs in O(n) time and uses O(n) extra memory.
Tracing the example
The adjacency lists are adj[0] = [1, 2], adj[1] = [0, 3, 4], adj[2] = [0, 5], and the leaves list only their parent. Because a stack is last-in, first-out, the last child pushed is the first child explored.
| Step | Popped | Pushed | Stack after | Order so far |
|---|---|---|---|---|
| 1 | 0 | 1, 2 | [1, 2] | 0 |
| 2 | 2 | 5 | [1, 5] | 0, 2 |
| 3 | 5 | none | [1] | 0, 2, 5 |
| 4 | 1 | 3, 4 | [3, 4] | 0, 2, 5, 1 |
| 5 | 4 | none | [3] | 0, 2, 5, 1, 4 |
| 6 | 3 | none | [] | 0, 2, 5, 1, 4, 3 |
The reversed order is 3, 4, 1, 5, 2, 0. The size loop then runs as follows: 3 adds 1 to size[1], giving 2. Node 4 adds 1 more, giving 3. Node 1 adds 3 to size[0], giving 4. Node 5 makes size[2] equal 2. Node 2 adds 2 to size[0], giving 6. Every child is added to its parent before the parent passes its own total upward.
It is a genuine DFS pre-order
This stack order is a real depth-first pre-order, not just some order where parents come first. When u is popped, all of its children are pushed together. The top child is then popped, and its entire subtree is handled before anything below it on the stack, including its siblings, comes back up. As a result, the subtree of u occupies a contiguous block of order starting at u's position:
from itertools import combinations # not needed; standard library only below
def subtree_blocks(n, edges, root=0):
parent, order, size = root_tree(n, edges, root)
pos = [0] * n
for i, u in enumerate(order):
pos[u] = i
return {u: order[pos[u]:pos[u] + size[u]] for u in range(n)}
def root_tree(n, edges, root=0):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent = [-1] * n
seen = [False] * n
seen[root] = True
order = []
stack = [root]
while stack:
u = stack.pop()
order.append(u)
for v in adj[u]:
if not seen[v]:
seen[v] = True
parent[v] = u
stack.append(v)
size = [1] * n
for u in reversed(order):
if parent[u] != -1:
size[parent[u]] += size[u]
return parent, order, size
if __name__ == "__main__":
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5)]
for u, block in subtree_blocks(6, edges).items():
print(u, block)
# 0 [0, 2, 5, 1, 4, 3]
# 1 [1, 4, 3]
# 2 [2, 5]
# ...You will not need this property for the DP in this tutorial. It is still worth knowing, because it lets the same traversal answer "is a an ancestor of b?" with pos[a] <= pos[b] < pos[a] + size[a]. It also lets you flatten subtree queries into range queries on an array.
Alternative: an explicit post-order
Sometimes you want each node emitted at the moment its subtree finishes. One example is releasing memory for child tables as soon as the parent has merged them, which the tree knapsack chapter does. The standard technique is to push every node twice, once to expand it and once to finish it:
def postorder(n, edges, root=0):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent = [-1] * n
order = []
stack = [(root, -1, False)]
while stack:
u, p, done = stack.pop()
if done:
order.append(u) # all of u's children are already in order
continue
parent[u] = p
stack.append((u, p, True)) # finish u after its children
for v in adj[u]:
if v != p:
stack.append((v, u, False))
return parent, order
if __name__ == "__main__":
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5)]
print(postorder(6, edges)) # ([-1, 0, 0, 1, 1, 2], [5, 2, 4, 3, 1, 0])The finish entry for u is pushed below the entries for its children, so it is popped only after every child and every child's descendants have been finished. This version relies on v != p instead of a seen array. That check is safe only when the input really is a tree, because any cycle would make the loop run forever.
For bottom-up DP, the two approaches give equivalent results. Reversed pre-order is shorter and pushes half as many stack entries, which is why the rest of the tutorial uses it.
Alternative: reversed BFS order
Breadth-first search assigns parents in the same way and visits nodes level by level. Reversing the BFS order processes the deepest level first, which also puts children before parents:
from collections import deque
def bfs_order(n, edges, root=0):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent = [-1] * n
seen = [False] * n
seen[root] = True
order = []
q = deque([root])
while q:
u = q.popleft()
order.append(u)
for v in adj[u]:
if not seen[v]:
seen[v] = True
parent[v] = u
q.append(v)
return parent, order
if __name__ == "__main__":
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5)]
parent, order = bfs_order(6, edges)
size = [1] * 6
for u in reversed(order):
if parent[u] != -1:
size[parent[u]] += size[u]
print(order, size) # [0, 1, 2, 3, 4, 5] [6, 3, 2, 1, 1, 1]BFS order works for any DP that only needs the children-before-parents property. It does not give contiguous subtree blocks, so prefer the DFS version if you might later need ancestor checks or subtree ranges.
Common errors and edge cases
Other mistakes that show up often:
- Marking
seenwhen a node is popped instead of when it is pushed. On a valid tree this happens to work. If the input contains a cycle, a node can be pushed twice and appear inordertwice, and the DP counts it twice. Marking at push time keeps each node to one stack entry. - Relying only on
v != parent. If the input has duplicate edges, the parent shows up twice in a child's adjacency list. The second copy passes the check and the traversal follows it back. Aseenarray handles both cycles and duplicate edges. - Indexing problems. Many problem statements number nodes from 1. Either allocate
n + 1slots or subtract 1 from each endpoint while reading the input, and do it the same way in every array. - A single node. With
n = 1and no edges,orderis[root], the bottom-up loop does nothing, andsize[root] = 1. Make sure later DPs also handle a root with no children. - Forests. If the graph may be disconnected, one traversal from node 0 leaves the other components unvisited. Start a new traversal from every node with
seen[u]still false, and add each new start node to the sameorderlist. Each component's nodes form a contiguous run, so the reversed order still puts children before parents. - Skipping input validation. A tree on n nodes has exactly n − 1 edges and is connected. If you can't trust the input, check that
len(order) == nafter the traversal and that the edge count is n − 1.
Summary of the pattern
Every bottom-up tree DP in the rest of this tutorial has the same structure:
def bottom_up_template(n, edges, root=0):
parent, order, _ = root_tree(n, edges, root)
dp = [0] * n # initialise each node's own state
for u in reversed(order): # children are finished before u
p = parent[u]
if p != -1:
dp[p] += dp[u] + 1 # replace with the problem's transition
return dp
def root_tree(n, edges, root=0):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent = [-1] * n
seen = [False] * n
seen[root] = True
order = []
stack = [root]
while stack:
u = stack.pop()
order.append(u)
for v in adj[u]:
if not seen[v]:
seen[v] = True
parent[v] = u
stack.append(v)
size = [1] * n
for u in reversed(order):
if parent[u] != -1:
size[parent[u]] += size[u]
return parent, order, size
if __name__ == "__main__":
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5)]
print(bottom_up_template(6, edges)) # descendants per node: [5, 2, 1, 0, 0, 0]In this template, a child pushes its finished value into its parent instead of the parent pulling values from a list of children. That way you never need to store explicit child lists, and each tree edge is handled exactly once.
Exercise
In root_tree, suppose the line order.append(u) is moved so that it runs right after stack.append(v) inside the loop, appending v instead of u (and the root is appended once before the loop). Does reversed(order) still put children before parents? Explain.
Show answer
Yes. Under that change, each node is appended at the moment it is discovered, and a node is discovered only while its parent is being expanded. The parent was discovered earlier, so it was appended earlier. Every parent therefore still comes before its children in order, and reversing the list puts children first. What changes is that order is no longer a DFS pre-order: it groups siblings together, so subtrees are no longer contiguous blocks.
Exercise
Write a function depths(n, edges, root=0) that returns the depth of every node (the root has depth 0) and the height of every node (the number of edges on the longest downward path to a leaf). Use one traversal and no recursion. Which direction of order does each quantity need?
Show answer
Depth is a top-down quantity, so walk order forwards: depth[u] = depth[parent[u]] + 1 for every non-root u. Height is a bottom-up quantity, so walk reversed(order): for each non-root u, set height[parent[u]] = max(height[parent[u]], height[u] + 1), with every height starting at 0. Both loops reuse the parent and order returned by a single call to root_tree, and each runs in O(n).
Exercise
A test case is a path of 10^6 nodes given in random label order. Which of these succeed in CPython: (a) the recursive DFS with the default limit, (b) the recursive DFS after sys.setrecursionlimit(10**7), (c) root_tree?
Show answer
(a) fails with RecursionError at about 1000 frames deep. (b) usually crashes the process with a segmentation fault, because a million Python frames overflow the C stack even though the Python-level limit allows them. (c) succeeds: its memory use is a list-based stack of at most n entries on the heap, and it runs in O(n) time no matter how deep the tree is.