#834
Sum of Distances in Tree
HardDynamic ProgrammingTreeDepth-First SearchGraph TheoryDepth-First Search (DFS)Dynamic Programming on Trees
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach leverages the tree structure to calculate distances efficiently. By using a two-pass DFS, we can compute the distances in linear time.
⚙️
Algorithm
3 steps- 1Step 1: Perform a DFS from an arbitrary root (e.g., node 0) to calculate the initial distances and subtree sizes.
- 2Step 2: Use the results from the first DFS to compute the distances for all nodes based on the parent's distance.
- 3Step 3: Return the final distances for all nodes.
solution.py26 lines
1def sumOfDistancesInTree(n, edges):
2 from collections import defaultdict
3 graph = defaultdict(list)
4 for a, b in edges:
5 graph[a].append(b)
6 graph[b].append(a)
7
8 answer = [0] * n
9 count = [1] * n
10
11 def dfs1(node, parent):
12 for neighbor in graph[node]:
13 if neighbor != parent:
14 dfs1(neighbor, node)
15 count[node] += count[neighbor]
16 answer[node] += answer[neighbor] + count[neighbor]
17
18 def dfs2(node, parent):
19 for neighbor in graph[node]:
20 if neighbor != parent:
21 answer[neighbor] = answer[node] - count[neighbor] + (n - count[neighbor])
22 dfs2(neighbor, node)
23
24 dfs1(0, -1)
25 dfs2(0, -1)
26 return answerℹ
Complexity note: The time complexity is O(n) because we perform two DFS traversals of the tree, each visiting every node once.
- 1Understanding tree traversal is crucial for solving tree-related problems efficiently.
- 2Using properties of trees (like subtree sizes) can help optimize calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.