Graph Theory37 sections · 1633 units
Open in Course

The Single-Root Problem (Why you need rerooting)

(The $O(n^2)$ problem)

Suppose you want to compute, for every node vv in a tree, the sum of distances from vv to all other nodes. You already know how to do this for one fixed root using a single DFS. Root the tree at node 11, run DFS, collect subtree sizes and distance sums.

But now you need the answer for node 22, node 33, and every other node. The brute force approach is to re-run DFS from each node separately. That gives O(n)O(n) per node and O(n2)O(n^2) total. With n=200,000n = 200{,}000, that is 4×10104 \times 10^{10} operations. Far too slow.