LeetCode 题解工作台
树中距离之和
给定一个无向、连通的树。树中有 n 个标记为 0...n-1 的节点以及 n-1 条边 。 给定整数 n 和数组 edges , edges[i] = [a i , b i ] 表示树中的节点 a i 和 b i 之间有一条边。 返回长度为 n 的数组 answer ,其中 answer[i] 是树…
4
题型
5
代码语言
3
相关题
当前训练重点
困难 · 图·DFS·traversal
答案摘要
我们先跑一遍 DFS,计算出每个节点的子树大小,记录在数组 中,并且统计出节点 到其他节点的距离之和,记录在 中。 接下来,我们再跑一遍 DFS,枚举每个点作为根节点时,其他节点到根节点的距离之和。假设当前节点 的答案为 ,当我们从节点 转移到节点 时,距离之和变为 $t - size[j] + n - size[j]$,即距离节点 及其子树节点的距离之和减少 ,而距离其它节点的距离…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 图·DFS·traversal 题型思路
题目描述
给定一个无向、连通的树。树中有 n 个标记为 0...n-1 的节点以及 n-1 条边 。
给定整数 n 和数组 edges , edges[i] = [ai, bi]表示树中的节点 ai 和 bi 之间有一条边。
返回长度为 n 的数组 answer ,其中 answer[i] 是树中第 i 个节点与所有其他节点之间的距离之和。
示例 1:

输入: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]] 输出: [8,12,6,10,10,10] 解释: 树如图所示。 我们可以计算出 dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) 也就是 1 + 1 + 2 + 2 + 2 = 8。 因此,answer[0] = 8,以此类推。
示例 2:
输入: n = 1, edges = [] 输出: [0]
示例 3:
输入: n = 2, edges = [[1,0]] 输出: [1,1]
提示:
1 <= n <= 3 * 104edges.length == n - 1edges[i].length == 20 <= ai, bi < nai != bi- 给定的输入保证为有效的树
解题思路
方法一:树形 DP(换根)
我们先跑一遍 DFS,计算出每个节点的子树大小,记录在数组 中,并且统计出节点 到其他节点的距离之和,记录在 中。
接下来,我们再跑一遍 DFS,枚举每个点作为根节点时,其他节点到根节点的距离之和。假设当前节点 的答案为 ,当我们从节点 转移到节点 时,距离之和变为 ,即距离节点 及其子树节点的距离之和减少 ,而距离其它节点的距离之和增加 。
时间复杂度 ,空间复杂度 。其中 为树的节点数。
相似题目:
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate should demonstrate familiarity with tree traversal algorithms.
- question_mark
The candidate must efficiently propagate calculations from one node to others.
- question_mark
Look for a clear understanding of how dynamic programming can optimize the process.
常见陷阱
外企场景- error
Misunderstanding the relationship between the sum of distances for a parent and its children, leading to inefficient recomputation.
- error
Failing to use dynamic programming, resulting in redundant calculations and a time complexity that exceeds acceptable limits.
- error
Not properly handling edge cases, such as when `n = 1` or `n = 2`.
进阶变体
外企场景- arrow_right_alt
Modify the problem to calculate the sum of distances for a specific subset of nodes rather than all nodes.
- arrow_right_alt
Alter the tree structure by introducing different types of edges (e.g., weighted edges) and adjusting the solution approach.
- arrow_right_alt
Explore the problem using a breadth-first search (BFS) approach instead of DFS to see how the complexity and approach might change.