Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 834 Sum of Distances in Tree - Problem Statement

LeetCode 834

Given a tree, for each node ii, compute the sum of distances from ii to all other nodes. Distance = number of edges. Example: Tree with edges [[0,1],[0,2],[2,3],[2,4],[2,5]][[0,1],[0,2],[2,3],[2,4],[2,5]].

Answer: [8,12,6,10,10,10][8,12,6,10,10,10]. Node 22 has the smallest sum (66) because it's most central. With naive BFS from each node, you'd get O(n2)O(n^2). Let's solve it in O(n)O(n) with rerooting.