Sum of Distances in Tree — LeetCode 834 Python Solution

HardTreeDepth-First SearchGraphDynamic Programming
Problem
#834
Reading time
5 min

The 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] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

Example

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.

Python solution

Python
class Solution:
    def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
        def dfs1(i: int, fa: int, d: int):
            ans[0] += d
            size[i] = 1
            for j in g[i]:
                if j != fa:
                    dfs1(j, i, d + 1)
                    size[i] += size[j]

        def dfs2(i: int, fa: int, t: int):
            ans[i] = t
            for j in g[i]:
                if j != fa:
                    dfs2(j, i, t - size[j] + n - size[j])

        g = defaultdict(list)
        for a, b in edges:
            g[a].append(b)
            g[b].append(a)

        ans = [0] * n
        size = [0] * n
        dfs1(0, -1, 0)
        dfs2(0, -1, ans[0])
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the number of nodes in the tree auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 834. Sum of Distances in Tree is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 834. Sum of Distances in Tree?
LeetCode 834. Sum of Distances in Tree is rated Hard on LeetCode.
What is the time complexity of LeetCode 834. Sum of Distances in Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 834. Sum of Distances in Tree?
The Python solution on this page uses O(n), where n is the number of nodes in the tree auxiliary space.
What topics does LeetCode 834. Sum of Distances in Tree cover?
LeetCode 834. Sum of Distances in Tree is tagged Tree, Depth-First Search, Graph and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview