LeetCode 题解工作台
包含要求路径的最小带权子图 II
给你一个 无向带权 树,共有 n 个节点,编号从 0 到 n - 1 。这棵树由一个二维整数数组 edges 表示,长度为 n - 1 ,其中 edges[i] = [u i , v i , w i ] 表示存在一条连接节点 u i 和 v i 的边,权重为 w i 。 此外,给你一个二维整数数组 …
3
题型
0
代码语言
3
相关题
当前训练重点
困难 · 二分·树·traversal
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给你一个 无向带权 树,共有 n 个节点,编号从 0 到 n - 1。这棵树由一个二维整数数组 edges 表示,长度为 n - 1,其中 edges[i] = [ui, vi, wi] 表示存在一条连接节点 ui 和 vi 的边,权重为 wi。
此外,给你一个二维整数数组 queries,其中 queries[j] = [src1j, src2j, destj]。
返回一个长度等于 queries.length 的数组 answer,其中 answer[j] 表示一个子树的 最小总权重 ,使用该子树的边可以从 src1j 和 src2j 到达 destj 。
这里的 子树 是指原树中任意节点和边组成的连通子集形成的一棵有效树。
示例 1:
输入: edges = [[0,1,2],[1,2,3],[1,3,5],[1,4,4],[2,5,6]], queries = [[2,3,4],[0,2,5]]
输出: [12,11]
解释:
蓝色边表示可以得到最优答案的子树之一。

-
answer[0]:在选出的子树中,从src1 = 2和src2 = 3到dest = 4的路径总权重为3 + 5 + 4 = 12。 -
answer[1]:在选出的子树中,从src1 = 0和src2 = 2到dest = 5的路径总权重为2 + 3 + 6 = 11。
示例 2:
输入: edges = [[1,0,8],[0,2,7]], queries = [[0,1,2]]
输出: [15]
解释:

answer[0]:选出的子树中,从src1 = 0和src2 = 1到dest = 2的路径总权重为8 + 7 = 15。
提示:
3 <= n <= 105edges.length == n - 1edges[i].length == 30 <= ui, vi < n1 <= wi <= 1041 <= queries.length <= 105queries[j].length == 30 <= src1j, src2j, destj < nsrc1j、src2j和destj互不不同。- 输入数据保证
edges表示的是一棵有效的树。
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Understanding how to apply DFS/BFS with binary lifting is key to solving this problem efficiently.
- question_mark
The candidate should demonstrate awareness of tree traversal and path optimization strategies.
- question_mark
Look for candidates who focus on time complexity optimization when handling large input sizes.
常见陷阱
外企场景- error
Not efficiently handling large trees and queries, leading to timeouts or inefficient solutions.
- error
Overlooking the need to minimize the weight of the subtree for each query, which can lead to incorrect answers.
- error
Failing to apply binary lifting correctly, causing unnecessary recalculations of paths.
进阶变体
外企场景- arrow_right_alt
Optimizing the algorithm for a higher number of nodes and queries.
- arrow_right_alt
Extending the problem to support dynamic updates to the tree or queries.
- arrow_right_alt
Handling multiple types of tree structures beyond binary trees, such as general graphs.