![]() |
VOOZH | about |
You are given a tree consisting of n nodes. Your task is to determine for each node the sum of the distances from the node to all other nodes.
Example:
Input: edges = { { 1, 2 }, { 1, 3 }, { 3, 4 }, { 3, 5 } }
Output: 6 9 5 8 8Input: edges = { { 1, 2 }, { 2, 3 }, { 3, 4 }, { 3, 5 } }
Output: 9 6 5 8 8
Approach:
Lets see the intuition into steps
- Finding the sum of distances from a single node: If we root the tree at a particular node, we can use Depth-First Search (DFS) to find the depth of each other node. The sum of these depths gives us the sum of distances from the root node to all other nodes.
- Finding the sum of distances from all nodes: Doing the above for each node would be too slow if n is large. So, we need a faster way. The key is to use the answer for one node to quickly find the answer for its neighbors.
- Transitioning from one node to its neighbor: If we reroot the tree at a neighbor of the current root, the depths of all nodes in the new root’s subtree decrease by 1, and the depths of all nodes outside of its subtree increase by 1. This means the change in the sum of distances is exactly n - 2 * (size of new root's subtree).
- Calculating the answer for all nodes: We can use DFS twice to find the answer for all nodes. The first DFS finds the answer for one node and the size of each node’s subtree. The second DFS computes the answer for all nodes using the formula from step 3.
Steps-by-step approach:
Below is the implementation of the above approach:
6 9 5 8 8
Time Complexity: O(n)
Auxiliary Space: O(n)