> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Sum of Distances in Tree Python Solution

> Tested Python solution for LeetCode 834 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 834, [Hard](/catalog/hard). Topics: [Dynamic Programming](/catalog/topics/dynamic-programming), [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Graph Theory](/catalog/topics/graph-theory), DP on Trees. [View on LeetCode](https://leetcode.com/problems/sum-of-distances-in-tree/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 834   # by problem number
lcpy gen -s sum_of_distances_in_tree   # by problem name
```

## 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](https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist1.jpg)

```
Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation: The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer[0] = 8, and so on.
```

![Example 2](https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist2.jpg)

```
Input: n = 1, edges = []
Output: [0]
```

![Example 3](https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist3.jpg)

```
Input: n = 2, edges = [[1,0]]
Output: [1,1]
```

### 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](https://github.com/wislertt/leetcode-py/blob/main/leetcode/sum_of_distances_in_tree/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/sum_of_distances_in_tree/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n) build + two O(n) traversals
    # Space: O(n) adjacency, subtree counts and output
    def sum_of_distances_in_tree(self, n: int, edges: list[list[int]]) -> list[int]:
        graph: list[list[int]] = [[] for _ in range(n)]
        for a, b in edges:
            graph[a].append(b)
            graph[b].append(a)

        subtree_size = [1] * n
        answer = [0] * n

        # Post-order from root 0: count descendants and sum depths below each node.
        stack: list[tuple[int, int, bool]] = [(0, -1, False)]
        while stack:
            node, parent, processed = stack.pop()
            if not processed:
                stack.append((node, parent, True))
                for child in graph[node]:
                    if child != parent:
                        stack.append((child, node, False))
            else:
                for child in graph[node]:
                    if child != parent:
                        subtree_size[node] += subtree_size[child]
                        answer[node] += answer[child] + subtree_size[child]

        # Pre-order reroot: moving the root from parent to child shifts the sum by
        # size(child) closer minus (n - size(child)) farther.
        reroot_stack: list[tuple[int, int]] = [(0, -1)]
        while reroot_stack:
            node, parent = reroot_stack.pop()
            for child in graph[node]:
                if child != parent:
                    answer[child] = answer[node] + n - 2 * subtree_size[child]
                    reroot_stack.append((child, node))

        return answer
```

## Complexity

| Time | Space |
| - | - |
| O(n) build + two O(n) traversals | O(n) adjacency, subtree counts and output |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.