Graph Theory37 sections · 1633 units
Open in Course

Problem - Sum of Distances in Tree (LeetCode 834)

(LeetCode variant)

LeetCode 834834 is the same problem as CSES Tree Distances II with a different interface. You get an integer nn and an array of edges. Return an array where answer[i] is the sum of distances from node ii to all other nodes.

The difference from CSES: LeetCode uses 00-indexed nodes (nodes 00 through n1n-1), while CSES uses 11-indexed. Your rerooting logic stays identical. You only change the loop bounds and array indexing.

Try implementing the two-pass solution. Root at node 00, compute subtree sizes and distance sums in the down pass, then reroot in the up pass.