Graph Theory37 sections · 1633 units
Open in Course

CSES 1133 Tree Distances II - Algorithm

Two-pass DFS

1.1. Root the tree at node 11

2.2. First DFS: compute subtree size and sum of distances from node 11

3.3. Second DFS: reroot the tree by moving from parent to child, updating the sum using the formula Formula: When moving root from uu to child vv: - Nodes in subtree of vv (size svs_v) get closer by 11: subtract svs_v - Nodes outside subtree of vv (size nsvn - s_v) get farther by 11: add nsvn - s_v - New sum = old sum - svs_v + (nsv)(n - s_v) = old sum + n2svn - 2 \cdot s_v

This runs in O(n)O(n) time and uses O(n)O(n) space.