The "Sum of Distances in Tree" problem is a classic hard-level graph challenge. You are given an undirected connected tree with nodes. For each node , you need to calculate the sum of the distances from node to all other nodes in the tree. The distance between two nodes is the number of edges on the unique path connecting them. You must return an array containing these sums for all nodes.
This problem is a favorite at top-tier companies like Google, Uber, and Microsoft because it requires a deep understanding of tree properties and dynamic programming on trees. A naive approach would involve running a Breadth-First Search (BFS) or Depth-First Search (DFS) from every node, resulting in an O(N²) solution, which is too slow for large . The optimized solution uses a technique called "Re-rooting DP," which is a highly sophisticated skill that distinguishes senior-level candidates.
The pattern used is Re-rooting Dynamic Programming. It involves two DFS passes:
count[i]) and the sum of distances within each subtree (res[i]).u to v, the distance sum changes predictably: nodes in v's subtree become one edge closer, while all other nodes become one edge further away. The formula is: res[v] = res[u] - count[v] + (N - count[v]). This allows us to compute the answer for all nodes in O(N) time.Imagine a simple star tree: node 0 connected to nodes 1, 2, and 3.
res[1] = res[0] - count[1] + (4 - count[1]). Since count[1] = 1 (just itself), res[1] = 3 - 1 + 3 = 5.
This logic propagates through the entire tree.Master the "Re-rooting DP" technique. It is applicable to many tree problems where you need to calculate a property for every node as if it were the root. Practice the transition formula: how does the answer for a child differ from its parent?