<p>There is an undirected connected tree with <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code> and <code>n - 1</code> edges.</p>

<p>You are given the integer <code>n</code> and the array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.</p>

<p>Return an array <code>answer</code> of length <code>n</code> where <code>answer[i]</code> is the sum of the distances between the <code>i<sup>th</sup></code> node in the tree and all other nodes.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist1.jpg" style="width: 304px; height: 224px;" />
<pre>
<strong>Input:</strong> n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
<strong>Output:</strong> [8,12,6,10,10,10]
<strong>Explanation:</strong> 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.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist2.jpg" style="width: 64px; height: 65px;" />
<pre>
<strong>Input:</strong> n = 1, edges = []
<strong>Output:</strong> [0]
</pre>

<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/07/23/lc-sumdist3.jpg" style="width: 144px; height: 145px;" />
<pre>
<strong>Input:</strong> n = 2, edges = [[1,0]]
<strong>Output:</strong> [1,1]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>edges.length == n - 1</code></li>
	<li><code>edges[i].length == 2</code></li>
	<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li>
	<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
	<li>The given input represents a valid tree.</li>
</ul>

"""
For single "root" vertex: BFS/DFS from it, accumulate sum of all distances. O(N)
BFS from all vertices: O(N^2)

Recalculate function when moving from parent v to child u:
- size(v) - size of subtree with root in v
- we decrease distance by 1 for size(u) vertices
- we increase distance by 1 for (size(root) - size(u))

ans(u) = ans(v) - size(u) + (size(root) - size(u)) = ans(v) + size(root) - 2 * size(u)
size(v) can be calculated for all vertices during DFS in O(N)

O(N) algorithm:
First DFS: calculate answer and for root and size(v) for all vertices
Second DFS: calculate answer for other vertices using formulae
"""

class DistanceSumCalculator:
    def __init__(self, graph: List[List[int]]):
        self.graph = graph
        self.distances = [0 for _ in range(len(self.graph))]
        self._sizes = [0 for _ in range(len(self.graph))]
    
    def calculate(self):
        self._initial_dfs(-1, 0, 0)
        self._size_calculation_dfs(-1, 0)
    
    def _initial_dfs(self, parent: int, vertex: int, current_distance: int):
        self.distances[0] += current_distance
        current_size = 0
        for child in self.graph[vertex]:
            if child != parent:
                self._initial_dfs(vertex, child, current_distance + 1)
                current_size += self._sizes[child]
        self._sizes[vertex] = current_size + 1
    
    def _size_calculation_dfs(self, parent: int, vertex: int):
        for child in self.graph[vertex]:
            if child != parent:
                self.distances[child] = (
                    self.distances[vertex] 
                    + self._sizes[0] 
                    - 2 * self._sizes[child]
                )
                self._size_calculation_dfs(vertex, child)
    

def sum_of_distances_in_tree(graph: List[List[int]]) -> List[int]:
    calculator = DistanceSumCalculator(graph)
    calculator.calculate()
    return calculator.distances


def edges_to_adjacency_list(n: int, edges: List[List[int]]) -> List[List[int]]:
    graph = [[] for _ in range(n)]
    for u, v in edges:
        graph[u].append(v)
        graph[v].append(u)
    
    return graph


class Solution:
    def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
        graph = edges_to_adjacency_list(n, edges)
        return sum_of_distances_in_tree(graph)

34670