Sub topic 4
Warm-up: Subtree Sizes and Sums
This chapter assumes you have read the earlier chapters on rooting a tree and on iterative post-order. It also assumes you are comfortable with basic array DP and with Big-O notation. The goal here is to practice the pattern on the simplest possible states: one number per node, combined from its children. Every later chapter reuses this pattern.
The working model
A subtree aggregate is a value for node u that depends only on the nodes in u's subtree. If you can compute it from u's own data plus the finished values of its children, one reverse pass over the DFS order is enough.
Common examples:
| Aggregate | Base value at `u` | Combine child `c` into `u` | Direction |
|---|---|---|---|
| `size[u]` | 1 | `size[u] += size[c]` | bottom-up |
| `total[u]` (sum of values) | `value[u]` | `total[u] += total[c]` | bottom-up |
| `height[u]` (longest downward path, in edges) | 0 | `height[u] = max(height[u], height[c] + 1)` | bottom-up |
| `depth[u]` (distance from root) | 0 at root | `depth[c] = depth[u] + 1` | top-down |
Depth is in the table to show the contrast. It depends on the path above a node, not on the subtree below it, so it flows from parent to child. You compute it by walking the order forward instead of in reverse.
One pass for each direction
The root_tree helper from the earlier chapter returns parent and order. In order, every parent comes before its children. The code below repeats the helper so that it runs on its own.
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
def subtree_aggregates(n, edges, value, root=0):
parent, order, size = root_tree(n, edges, root)
# Bottom-up: a child is finished before its parent reads it.
total = list(value)
height = [0] * n
for u in reversed(order):
p = parent[u]
if p != -1:
total[p] += total[u]
height[p] = max(height[p], height[u] + 1)
# Top-down: a parent is finished before its child reads it.
depth = [0] * n
for u in order:
p = parent[u]
if p != -1:
depth[u] = depth[p] + 1
return size, total, height, depth
if __name__ == "__main__":
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5)]
value = [5, 3, 2, 1, 4, 6]
size, total, height, depth = subtree_aggregates(6, edges, value)
print("size ", size) # [6, 3, 2, 1, 1, 1]
print("total ", total) # [21, 8, 8, 1, 4, 6]
print("height", height) # [2, 1, 1, 0, 0, 0]
print("depth ", depth) # [0, 1, 1, 2, 2, 2]Each node is pushed and popped once, and each edge is scanned twice, so every pass is O(n). Neither pass uses recursion, so a path-shaped tree with 10^6 nodes will not hit Python's recursion limit.
Why "push into the parent" works
The loops never list a node's children. Instead, each node adds its finished value into its parent's slot. When the reverse loop reaches u, every descendant of u has already appeared later in order and has already been processed. By that point, total[u] has received every contribution it will ever get, so it is safe to pass on. This "push to parent" style avoids storing child lists. You will see it again in the independent set, diameter, and rerooting chapters.
Common errors
- Wrong direction. If you compute
depthin the reverse loop, each child reads its parent's depth before that depth is set. Ask whether the quantity describes what is below the node (reverse order) or what is above it (forward order). - Off-by-one in height. Decide whether height counts edges or nodes. The code above counts edges, so a leaf has height 0. Mixing the two conventions is the usual cause of diameter answers that are off by one.
- Overflow in other languages. Subtree sums of large values can exceed 32-bit integers in C++ or Java. Python's integers do not overflow, but ported code can.
- Treating the input as already rooted. An edge list says nothing about direction. Always derive
parentfrom a traversal; don't assumeuis the parent in the pair(u, v).
Exercises
Exercise
For each non-root node u, the edge (u, parent[u]) splits the tree into two parts. How many unordered pairs of nodes have a path that uses this edge? Use that to compute the sum of distances over all unordered pairs in the example tree.
Show answer
The edge separates size[u] nodes from n - size[u] nodes, so size[u] (n - size[u]) pairs cross it. In the example, with n = 6: node 1 gives 33 = 9, node 2 gives 24 = 8, and nodes 3, 4, and 5 give 15 = 5 each. The total is 9 + 8 + 15 = 32.
Exercise
Add a bottom-up aggregate leaves[u], the number of leaves in u's subtree. What is its base value, and what is the combine step?
Show answer
Start with leaves[u] = 0 for every node. Process nodes in reversed(order). When you reach u, if leaves[u] is still 0, no child has added anything, so u is a leaf: set leaves[u] = 1. Then, if u has a parent p, run leaves[p] += leaves[u]. A node's value is finished before it is pushed, because all of its children appear later in order and so are processed earlier in the reversed loop.