LeetCode 题解工作台
带权树中的最短路径
给你一个整数 n 和一个以节点 1 为根的无向带权树,该树包含 n 个编号从 1 到 n 的节点。它由一个长度为 n - 1 的二维数组 edges 表示,其中 edges[i] = [u i , v i , w i ] 表示一条从节点 u i 到 v i 的无向边,权重为 w i 。 Create…
5
题型
0
代码语言
3
相关题
当前训练重点
困难 · 二分·树·traversal
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给你一个整数 n 和一个以节点 1 为根的无向带权树,该树包含 n 个编号从 1 到 n 的节点。它由一个长度为 n - 1 的二维数组 edges 表示,其中 edges[i] = [ui, vi, wi] 表示一条从节点 ui 到 vi 的无向边,权重为 wi。
同时给你一个二维整数数组 queries,长度为 q,其中每个 queries[i] 为以下两种之一:
[1, u, v, w']– 更新 节点u和v之间边的权重为w',其中(u, v)保证是edges中存在的边。[2, x]– 计算 从根节点 1 到节点x的 最短 路径距离。
返回一个整数数组 answer,其中 answer[i] 是对于第 i 个 [2, x] 查询,从节点 1 到 x 的最短路径距离。
示例 1:
输入: n = 2, edges = [[1,2,7]], queries = [[2,2],[1,1,2,4],[2,2]]
输出: [7,4]
解释:

- 查询
[2,2]:从根节点 1 到节点 2 的最短路径为 7。 - 操作
[1,1,2,4]:边(1,2)的权重从 7 变为 4。 - 查询
[2,2]:从根节点 1 到节点 2 的最短路径为 4。
示例 2:
输入: n = 3, edges = [[1,2,2],[1,3,4]], queries = [[2,1],[2,3],[1,1,3,7],[2,2],[2,3]]
输出: [0,4,2,7]
解释:

- 查询
[2,1]:从根节点 1 到节点 1 的最短路径为 0。 - 查询
[2,3]:从根节点 1 到节点 3 的最短路径为 4。 - 操作
[1,1,3,7]:边(1,3)的权重从 4 改为 7。 - 查询
[2,2]:从根节点 1 到节点 2 的最短路径为 2。 - 查询
[2,3]:从根节点 1 到节点 3 的最短路径为 7。
示例 3:
输入: n = 4, edges = [[1,2,2],[2,3,1],[3,4,5]], queries = [[2,4],[2,3],[1,2,3,3],[2,2],[2,3]]
输出: [8,3,2,5]
解释:

- 查询
[2,4]:从根节点 1 到节点 4 的最短路径包含边(1,2)、(2,3)和(3,4),权重和为2 + 1 + 5 = 8。 - 查询
[2,3]:路径为(1,2)和(2,3),权重和为2 + 1 = 3。 - 操作
[1,2,3,3]:边(2,3)的权重从 1 变为 3。 - 查询
[2,2]:最短路径为 2。 - 查询
[2,3]:路径权重变为2 + 3 = 5。
提示:
1 <= n <= 105edges.length == n - 1edges[i] == [ui, vi, wi]1 <= ui, vi <= n1 <= wi <= 104- 输入保证
edges构成一棵合法的树。 1 <= queries.length == q <= 105queries[i].length == 2或4queries[i] == [1, u, v, w'],或者queries[i] == [2, x]1 <= u, v, x <= n(u, v)一定是edges中的一条边。1 <= w' <= 104
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on tree flattening O(n) and O(log n) per query using segment trees or BIT. Space complexity includes storing the tree structure, Euler tour indices, and segment/BIT data structures, totaling O(n). |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect questions on Euler tour flattening and subtree segment mapping.
- question_mark
Be ready to explain how dynamic edge updates affect distance computation.
- question_mark
Demonstrate understanding of combining DFS traversal with range-based data structures.
常见陷阱
外企场景- error
Not correctly mapping subtree ranges in the Euler tour leading to wrong updates.
- error
Failing to handle cumulative distance updates for dynamic edge weight changes.
- error
Assuming static edge weights and trying naive traversal for every query.
进阶变体
外企场景- arrow_right_alt
Queries may only ask distances without edge updates, simplifying to a standard DFS.
- arrow_right_alt
Tree could be rooted at any node, requiring rerooting techniques for correct distances.
- arrow_right_alt
Weighted tree could allow negative weights, requiring careful distance propagation to avoid incorrect sums.