Back to problems Sign in to unlock
Leetcode
Medium
Graphs
Trees
Tree DP
Recursion
Google
Meta
Sum of Distances in Tree
Compute, for every node in a tree, the sum of distances to all other nodes.
Acceptance 100%
Also Available On
Other platform versions and source mappings for the same problem.
Problem Statement
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.
Input Format
- An integer representing the number of nodes.
- A list of undirected edges, where each edge is a pair connecting two nodes.
Output Format
- Return an integer array
ansof length . ans[i]is the sum of shortest-path distances from node to every other node.
Constraints
- The graph is a tree: connected and acyclic
- Nodes are labeled from $0n-1$
- Edges are undirected and contain no duplicates
Examples
Sample cases returned by the problem API.
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
Unlock deeper context for this problem
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.
Guided hints
Editorial and discussion links
Concept map and variants
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.