Sub topic 2
Children Before Parents: Post-order and Iterative DFS
This chapter assumes you know depth-first search, adjacency lists, and basic array DP, and that you can read Python. It also builds on the previous chapter, where we rooted a tree and gave every node a parent.
A tree DP computes a value for each node from the values of its children. That rule has one hard requirement: a node may only be processed after all of its children are finished. Any order with this property is valid. Post-order, which visits a node after its subtrees, is the classic example, but it is not the only one.
Why not just recurse?
The obvious way to get post-order is a recursive DFS that handles a node after its recursive calls return. In Python, this breaks on deep trees. The default recursion limit is 1000 frames, and a path graph with 200,000 nodes needs 200,000 nested calls. Raising the limit with sys.setrecursionlimit swaps the RecursionError for a crash of the interpreter's C stack, which is harder to diagnose. Judges and test suites love path-shaped trees for exactly this reason.
The reversed pre-order trick
You don't need true post-order. Run an iterative DFS with an explicit stack and record each node when it is popped. A node is pushed only while its parent is being processed, so every parent appears in the list before all of its children. Reverse that list and every child appears before its parent, which is all the DP needs.
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, sizeThe final loop is the template for every DP in this tutorial. Walk reversed(order), and when you reach u its value is already complete, so you fold it into parent[u].
Tracing a small tree
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5)]
parent, order, size = root_tree(6, edges)
print(parent) # [-1, 0, 0, 1, 1, 2]
print(order) # [0, 2, 5, 1, 4, 3]
print(order[::-1]) # [3, 4, 1, 5, 2, 0]
print(size) # [6, 3, 2, 1, 1, 1]In the reversed order, node 1 comes after 3 and 4, and node 0 comes last. Node 5 appears between node 1 and node 2, so the order is not a "clean" post-order. The DP does not care, because each subtree's internal order is still correct.
Checking it on a deep tree
n = 200_000
path = [(i, i + 1) for i in range(n - 1)]
parent, order, size = root_tree(n, path)
print(size[0], size[n - 1]) # 200000 1No recursion is involved, so depth doesn't matter. Time and memory are both O(n).
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Marking `seen` when popping, not pushing | A node gets pushed twice in graphs with cycles. In a tree it still works but wastes work, and the code breaks if the input is not really a tree | Mark at push time, as above |
| Iterating `order` forward for a bottom-up DP | Parents read child values that are still at their initial state | Use `reversed(order)` |
| Using `parent[u] != -1` but rooting at a node whose parent is set elsewhere | The root is folded into a nonexistent parent, or `size[-1]` is updated silently | Keep the root's parent as -1, and remember that Python's `-1` index wraps around |
| Rebuilding the order inside every DP | Code duplication and O(n) extra work per pass | Compute `parent` and `order` once and reuse them |
A BFS order also places parents before children, so reversing a BFS order is equally valid. DFS and BFS differ only in stack versus queue. Pick whichever you find easier to read.
Exercise
You replace stack.pop() with stack.pop(0) (turning the DFS into a BFS). Does reversed(order) still give a valid children-before-parents order, and what new cost appears?
Show answer
Yes. A node still enters the list only after its parent has been popped, so parents still come before children and the reversal stays valid. But list.pop(0) is O(n), which makes the traversal O(n²). Use collections.deque with popleft() to keep it O(n).
Exercise
Using parent and order from root_tree, write a loop that computes depth[u], the number of edges from the root to u. Which direction do you iterate, and why?
Show answer
Iterate order forward, because depth flows from parent to child: depth = [0] * n; for u in order: if parent[u] != -1: depth[u] = depth[parent[u]] + 1. Each parent appears before its children, so depth[parent[u]] is already set when it is read.