Compute, for every node in a tree, the sum of distances to all other nodes.
You are given an undirected tree with nodes labeled from $0n-1ii$ to every other node in the tree.
Return an array where the -th value is the sum of distances from node to all other nodes.
Because the input graph is a tree, there is exactly one simple path between any two nodes.
ans of length .ans[i] is the sum of shortest-path distances from node to every other node.Example 1
Input
n = 6 edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output
[8,12,6,10,10,10]
Explanation
For node 0, distances to the others are 1, 1, 2, 2, and 2, for a sum of 8. Repeating this for every node gives the full array.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.