Everyone's Total Commute — Solution & Editorial
Rerooting: one post-order pass computes subtree sizes and the root's answer; then moving the root across an edge changes the sum by (N − 2·size[child]) — a second pre-order pass yields every node in O(1) each.
Complexity: O(N)
Watch out: The transition ans[c] = ans[p] − size[c] + (N − size[c]) — both terms, both signs.