I knew brute force was wrong the second I wrote it out.
Use a two-pass DFS approach: first compute subtree sizes and the sum of distances from the root to all nodes, then reroot the tree to compute the sum for every node in O(n) time. Explain the rerooting formula: when moving from parent to child, the sum changes by (n - 2*subtree_size[child]).
Pro tip: Emphasize that the rerooting technique avoids O(n^2) by reusing computations, and mention that this pattern generalizes to many tree DP problems. Also, clarify that the tree is connected and undirected, so the root can be chosen arbitrarily.
Confirm that the tree is connected and undirected, and that we need an O(n) solution. Discuss edge cases like n=1.
Pick any node (e.g., 0) as root. Perform a post-order DFS to compute subtree sizes and the sum of distances from the root to all other nodes.
When moving the root from a parent to a child, the sum of distances changes by (n - 2 * subtree_size[child]). Explain why: nodes in the child's subtree get closer by 1, others get farther by 1.
Using the formula, compute the sum for each child from the parent's sum. Traverse the tree to fill the result array.
State that the algorithm runs in O(n) time and O(n) space. Walk through a small example to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.