When you move the root from node to its child , every distance in the tree shifts. Nodes inside 's subtree are now edge closer to the root. There are size[v] such nodes, so the total distance decreases by size[v].
Nodes outside 's subtree are now edge farther from the root. There are n - size[v] such nodes, so the total distance increases by n - size[v].
Combining both: answer[v] = answer[u] - size[v] + (n - size[v]) = answer[u] + n - 2 * size[v]. This single formula lets you compute every node's answer from its parent's answer in .