There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Return an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.
Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation: The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8.Hence, answer[0] = 8, and so on.
Input: n = 1, edges = []
Output: [0]
Input: n = 2, edges = [[1,0]]
Output: [1,1]
The brute force approach calculates the distance for each node by performing a Depth First Search (DFS) from each node to every other node. This gives a clear idea of the problem but is inefficient due to repeatedly traversing the tree for each node.
This approach is clear but inefficient due to repeated calculations, making it not suitable for larger trees.
To optimize, we use dynamic programming and precompute sub-tree information to reuse calculations efficiently. We perform two DFS traversals, where the first one calculates the sum of distances from an arbitrary root (e.g., node 0) to all its sub-nodes, and the second adjusts these values from the root to other nodes using precomputed information.
count[node]: number of nodes in the subtree rooted at node.answer[0]: initial sum of distances from root node to all other nodes.