Sum of distances in tree

Write codeHard40 minGoogle style

Your task

Given an undirected tree with n nodes labeled 0..n-1 and its edge list, return an array res where res[i] is the sum of the distances from node i to every other node. A naive BFS from each node is O(n^2); instead use the rerooting technique: one post-order pass computes subtree sizes and the answer for the root, then one pre-order pass propagates each node's answer to its children in O(1) using res[child] = res[parent] - size[child] + (n - size[child]). Return res. n can be up to 3e4.

Examples

sum_of_distances(n: int, edges: list[list[int]]) -> list[int]
Example 1
Inputsum_of_distances(6, [[0, 1], [0, 2], [2, 3], [2, 4], [2, 5]])
Output[8, 12, 6, 10, 10, 10]