Problem Description
Given an undirected tree with n nodes labeled from 0 to n - 1 (and exactly n - 1 edges), compute for each node the sum of distances to all other nodes in the tree.
Key Insights
- Use tree dynamic programming with two DFS traversals.
- The first DFS computes, for each node, the sum of distances from that node’s subtree and the count of nodes in that subtree.
- The second DFS propagates the computed distances from the root to all children using the relation that adjusts the distances based on subtree sizes.
- This method avoids recomputation, leading to an efficient O(n) solution.
Space and Time Complexity
Time Complexity: O(n) Space Complexity: O(n) (due to tree adjacency list and recursion stack)
Solution
We use a two-step DFS approach:
- In the first DFS (postorder), for each node we compute:
- count[node]: number of nodes in the subtree (including itself).
- res[node]: sum of distances from node to all nodes in its subtree.
- In the second DFS (preorder), we use the parent’s result to update each child’s result:
- When moving from parent to child, update res[child] = res[parent] - count[child] + (n - count[child]).
- This transformation works because moving to a child subtracts the distance for all nodes in the child’s subtree (as they get closer by 1) and adds the distance for the rest (as they get farther by 1).
The main data structures used are an adjacency list for the tree and two arrays (or vectors) to store the count and results. The algorithm leverages recursion to do DFS traversals.