Sub topic 8
Rerooting: Every Node as the Root in Linear Time
Many tree problems ask for one answer per node. Typical examples are the sum of distances from each node to all others, or the distance from each node to the farthest node. The obvious method roots the tree at every node and runs a full DP each time. That costs O(n) per root and O(n²) in total, which is too slow once n reaches 10⁵ or more.
Rerooting gets all n answers in O(n). You run the usual bottom-up DP once, from a fixed root. Then a second, top-down pass moves the root across one edge at a time. Each move reuses the previous answer and changes it in O(1).
This chapter assumes you know the root_tree helper from earlier chapters. It returns parent, a pre-order order in which every parent comes before its children, and subtree size. It also assumes you know subtree aggregates and how to combine branches through a node, as in the diameter chapter.
The Core Idea: Two Passes Over the Same Order
Root the tree at node 0. For every node u, the bottom-up pass computes down[u], a summary of u's subtree only. The answer for node 0 is complete after this pass, because node 0's subtree is the whole tree.
For any other node u, the tree splits into two parts:
u's own subtree, already summarized bydown[u];- everything else, which hangs off
uthrough its parent edge.
The missing piece is a summary of that second part. Call it up[u]. The top-down pass computes up[u] from the parent's values. Then the answer for u combines down[u] and up[u].
The two passes use the same order in opposite directions. Reversed pre-order guarantees that all children are finished before their parent. Forward pre-order guarantees that the parent is finished before its children. Both passes are loops, so deep trees such as a path of 10⁵ nodes cannot overflow the recursion stack.
Worked Example: Sum of Distances to All Nodes
The task is to compute ans[u], the sum of dist(u, v) over all nodes v, for every u.
The bottom-up pass
Let down[u] be the sum of distances from u to the nodes in its subtree. A child c contributes down[c] plus one extra edge for each of the size[c] nodes under it:
down[u] = sum over children c of (down[c] + size[c])
After this pass, ans[0] = down[0].
The rerooting step
Suppose ans[p] is known and u is a child of p. Move the root from p to u across the edge p–u:
- the
size[u]nodes inu's subtree each get one step closer; - the other
n - size[u]nodes each get one step farther.
So ans[u] = ans[p] - size[u] + (n - size[u]).
Only size[u] is needed for this step, so up[u] never has to be stored. That is the simplest form of rerooting: the change in the answer across an edge has a closed form.
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 sum_of_distances(n, edges):
parent, order, size = root_tree(n, edges, 0)
down = [0] * n # sum of distances from u to nodes in its subtree
for u in reversed(order):
p = parent[u]
if p != -1:
down[p] += down[u] + size[u]
ans = [0] * n
ans[0] = down[0]
for u in order:
p = parent[u]
if p != -1:
ans[u] = ans[p] - size[u] + (n - size[u])
return ans
edges = [(0, 1), (0, 2), (2, 3), (2, 4)]
print(sum_of_distances(5, edges)) # [6, 9, 5, 8, 8]Tracing it
The tree has node 0 joined to nodes 1 and 2, and node 2 joined to nodes 3 and 4.
| Node | size | down | Rerooting step | ans |
|---|---|---|---|---|
| 0 | 5 | 6 | root | 6 |
| 1 | 1 | 0 | 6 − 1 + 4 | 9 |
| 2 | 3 | 2 | 6 − 3 + 2 | 5 |
| 3 | 1 | 0 | 5 − 1 + 4 | 8 |
| 4 | 1 | 0 | 5 − 1 + 4 | 8 |
You can check node 2 by hand. Nodes 0, 3, and 4 are each at distance 1, and node 1 is at distance 2, for a total of 5.
The General Pattern: Computing `up[u]` Explicitly
Most problems have no closed form like the one above. In those problems you compute up[u], the summary of the part of the tree outside u's subtree as seen from u. Seen from p, that outside part consists of:
- the part outside
p's subtree, which isup[p]; - the subtrees of
u's siblings, the other children ofp.
Moving from p to u adds one edge. So up[u] is "extend by the edge p–u" applied to the combination of up[p] and every sibling contribution.
The hard part is the sibling contribution. You need "all children of p except u", and you need it for every u. Recomputing it for each child costs O(deg(p)) per child, which is O(deg²) for a node with many children. A star with 10⁵ leaves then takes about 10¹⁰ steps. You have three standard ways to get the "all except one" value in O(1).
| Technique | Works when | Cost per node p | Example |
|---|---|---|---|
| Subtract the child | combine is invertible (+, xor) | O(1) per child | sums, counts |
| Keep top two values | combine is max or min | O(deg) once | farthest distance |
| Prefix and suffix arrays | any associative combine | O(deg) once | products mod a prime, general monoids |
Example With a Non-invertible Combine: Farthest Distance From Every Node
Now compute ecc[u], the distance from u to the farthest node. This value is called the eccentricity of u. The combine here is max, and you cannot "subtract" a child from a max.
State definitions
best1[u]is the longest downward path fromu, in edges. It is the largestdown[c] + 1over the childrenc.best2[u]is the second-largest such value, counting ties.who[u]is the child that achievesbest1[u].up[u]is the longest path that starts atuand leaves through the parent edge.
The transition for up is:
up[u] = 1 + max(up[p], best sibling branch of p)
The best sibling branch is best2[p] if u itself supplied best1[p], and best1[p] otherwise. Then ecc[u] = max(best1[u], up[u]).
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 eccentricities(n, edges):
parent, order, _ = root_tree(n, edges, 0)
best1 = [0] * n # longest downward path from u
best2 = [0] * n # second longest, from a different child
who = [-1] * n # child giving best1
for u in reversed(order):
p = parent[u]
if p != -1:
cand = best1[u] + 1
if cand > best1[p]:
best2[p] = best1[p]
best1[p] = cand
who[p] = u
elif cand > best2[p]:
best2[p] = cand
up = [0] * n # longest path from u that starts with the edge to its parent
for u in order:
p = parent[u]
if p != -1:
sibling = best2[p] if who[p] == u else best1[p]
up[u] = 1 + max(up[p], sibling)
return [max(best1[u], up[u]) for u in range(n)]
edges = [(0, 1), (0, 2), (2, 3), (2, 4)]
print(eccentricities(5, edges)) # [2, 3, 2, 3, 3]Ties work out correctly. When two children of node 2 both give 1, the first sets best1[2] = 1, and the second fails cand > best1 but passes cand > best2, so best2[2] = 1. Each of them then sees its sibling's equal branch.
Leaves and the root need no special cases. A leaf has best1 = 0. The root has up = 0, which matches "no path leaves through a parent". This works because every value here is nonnegative. If branches can have negative values, as in a maximum path sum with negative weights, use −∞ for "no branch". Then decide on purpose whether an empty path of value 0 is allowed.
Prefix and Suffix Arrays: The Fully General Tool
When the combine is associative but has no inverse, and "top two" does not apply, use prefix and suffix arrays. Products modulo a prime are the usual case, because a factor can be 0 mod p and then you cannot divide it out. For each node p, with children listed as c_0 … c_{d-1} and contributions f(c_i):
pre[i]is the combination off(c_0) … f(c_{i-1});suf[i]is the combination off(c_{i+1}) … f(c_{d-1}).
The combination of all children except c_i is pre[i] ⊕ suf[i], and you then also fold in up[p]. Building the arrays costs O(deg(p)) at each node. Since the degrees sum to 2(n − 1), the whole pass is O(n).
Checking Against Brute Force
Rerooting formulas are easy to get slightly wrong, for example off by one at the root or with siblings swapped. Compare against an O(n²) BFS on small random trees before you trust the fast version.
import random
from collections import deque
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 sum_of_distances(n, edges):
parent, order, size = root_tree(n, edges, 0)
down = [0] * n
for u in reversed(order):
p = parent[u]
if p != -1:
down[p] += down[u] + size[u]
ans = [0] * n
ans[0] = down[0]
for u in order:
p = parent[u]
if p != -1:
ans[u] = ans[p] - size[u] + (n - size[u])
return ans
def bfs_dist(n, adj, s):
dist = [-1] * n
dist[s] = 0
q = deque([s])
while q:
u = q.popleft()
for v in adj[u]:
if dist[v] == -1:
dist[v] = dist[u] + 1
q.append(v)
return dist
def brute(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return [sum(bfs_dist(n, adj, s)) for s in range(n)]
for _ in range(500):
n = random.randint(1, 12)
edges = [(i, random.randrange(i)) for i in range(1, n)]
assert sum_of_distances(n, edges) == brute(n, edges), edges
print("all tests passed")The generator (i, random.randrange(i)) attaches each new node to an earlier one, so it always produces a valid tree. It also covers the case n = 1, which has no edges.
Common Errors
- Wrong pass direction. The top-down pass must walk
orderforward. If you walk it in reverse, children read their parent'sansorupbefore it has been set. - Recursion. A recursive rerooting on a path of 2·10⁵ nodes exceeds Python's default recursion limit. Raising the limit can still crash the interpreter. Use the two loops.
- Counting the child's own branch. You forget to exclude
uwhen you compute the sibling contribution. Thenup[u]includes a path that goes up topand straight back down intou, so the answer comes out too large. - Forgetting the extra edge.
up[u]needs the+1(or the edge weight) for the edgep–u. Sibling branches already include their own edge topinbest1. - Subtracting through max or a modular product. Neither operation has a usable inverse. Use top-two values or prefix and suffix arrays.
- Quadratic sibling loops. Looping over all siblings separately for each child is O(deg²) and blows up on star-shaped trees.
- Weighted edges. Replace each
+1with the edge weight. For sum of distances, the rerooting step becomesans[u] = ans[p] + w * (n - 2 * size[u]), wherewis the weight of edgep–u.
Exercises
Exercise
For the path 0–1–2–3 (n = 4), compute size, down, and the final sum-of-distances answer for every node using the rerooting formula.
Show answer
Rooted at 0: size = [4, 3, 2, 1]; down = [6, 3, 1, 0]. ans[0] = 6. ans[1] = 6 − 3 + 1 = 4. ans[2] = 4 − 2 + 2 = 4. ans[3] = 4 − 1 + 3 = 6. Result: [6, 4, 4, 6].
Exercise
In eccentricities, why is it wrong to set up[u] = 1 + max(up[p], best1[p]) for every child u?
Show answer
If u is the child that gives best1[p], then best1[p] is the path that goes from p back down through u. Using it counts a path that leaves u and returns into u's own subtree, which is not a simple path. That gives a value larger than the true eccentricity. The child that supplies best1[p] must use best2[p].
Exercise
You want, for every node u, the number of ways to choose a connected set of nodes that contains u, modulo 10^9 + 7. Rooted at 0, down[u] = product over children c of (down[c] + 1). Describe the up pass and explain why you should not divide by (down[u] + 1).
Show answer
Define up[u] as the number of connected sets that contain p but lie outside u's subtree, plus 1 for choosing nothing on that side. Then up[u] = (up[p] · product over siblings s of (down[s] + 1)) + 1, where up[root] = 1. The answer is ans[u] = down[u] · up[u]. Compute the sibling products with prefix and suffix products over p's children. Dividing by (down[u] + 1) fails when that value is 0 mod 10^9 + 7, because it has no modular inverse.