Skip to main content
LeetCode 834, Hard. Topics: Dynamic Programming, Tree, Depth-First Search, Graph Theory, DP on Trees. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:

Problem

There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given the integer n and the array edges where edges[i] = [a<sub>i</sub>, b<sub>i</sub>] indicates that there is an edge between nodes a<sub>i</sub> and b<sub>i</sub> in the tree. Return an array answer of length n where answer[i] is the sum of the distances between the i<sup>th</sup> node in the tree and all other nodes.

Examples

Example 1
Example 2
Example 3

Constraints

  • 1 <= n <= 3 * 10^4
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 <= a<sub>i</sub>, b<sub>i</sub> < n
  • a<sub>i</sub> != b<sub>i</sub>
  • The given input represents a valid tree.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026