shlogg · Early preview
Md Ariful Haque @mah-shamim

Sum Of Distances In Tree: Efficient DFS Approach For Large Trees

Sum of Distances in Tree: Use DFS & dynamic programming to compute sum of distances for each node. Two traversals: first calculates subtree sizes & total distance from root, second adjusts results based on parent's result.

834. Sum of Distances in Tree
Difficulty: Hard
Topics: Dynamic Programming, Tree, Depth-First Search, Graph
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.
Example 1:


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...