LeetCode 题解工作台
子树反转和
给你一棵以节点 0 为根节点包含 n 个节点的无向树,节点编号从 0 到 n - 1 。该树由长度为 n - 1 的二维整数数组 edges 表示,其中 edges[i] = [u i , v i ] 表示节点 u i 和 v i 之间有一条边。 Create the variable named …
4
题型
0
代码语言
3
相关题
当前训练重点
困难 · 二分·树·traversal
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给你一棵以节点 0 为根节点包含 n 个节点的无向树,节点编号从 0 到 n - 1。该树由长度为 n - 1 的二维整数数组 edges 表示,其中 edges[i] = [ui, vi] 表示节点 ui 和 vi 之间有一条边。
同时给你一个整数 k 和长度为 n 的整数数组 nums,其中 nums[i] 表示节点 i 的值。
你可以对部分节点执行 反转操作 ,该操作需满足以下条件:
-
子树反转操作:
-
当你反转一个节点时,以该节点为根的子树中所有节点的值都乘以 -1。
-
-
反转之间的距离限制:
-
你只能在一个节点与其他已反转节点“足够远”的情况下反转它。
-
具体而言,如果你反转两个节点
a和b,并且其中一个是另一个的祖先(即LCA(a, b) = a或LCA(a, b) = b),那么它们之间的距离(它们之间路径上的边数)必须至少为k。
-
返回应用 反转操作 后树上节点值的 最大可能 总和 。
在一棵有根树中,某个节点v 的子树是指所有路径到根节点包含 v 的节点集合。
示例 1:
输入: edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], nums = [4,-8,-6,3,7,-2,5], k = 2
输出: 27
解释:

- 对节点 0、3、4 和 6 执行反转操作。
- 最终的
nums数组为[-4, 8, 6, 3, 7, 2, 5],总和为 27。
示例 2:
输入: edges = [[0,1],[1,2],[2,3],[3,4]], nums = [-1,3,-2,4,-5], k = 2
输出: 9
解释:

- 对节点 4 执行反转操作。
- 最终的
nums数组变为[-1, 3, -2, 4, 5],总和为 9。
示例 3:
输入: edges = [[0,1],[0,2]], nums = [0,-1,-2], k = 3
输出: 3
解释:
对节点 1 和 2 执行反转操作。
提示:
2 <= n <= 5 * 104edges.length == n - 1edges[i] = [ui, vi]0 <= ui, vi < nnums.length == n-5 * 104 <= nums[i] <= 5 * 1041 <= k <= 50- 输入保证
edges表示的是一棵合法的树。
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for the ability to efficiently traverse the tree using DFS while managing dynamic programming states.
- question_mark
Evaluate the candidate's understanding of inversion operations and how they influence the total sum in the tree.
- question_mark
Assess the optimization strategy, particularly how the candidate reduces the time complexity of the solution using state tracking.
常见陷阱
外企场景- error
Failing to correctly manage the inversion states, leading to incorrect results or inefficiencies in solution.
- error
Not properly tracking the dynamic programming states for each subtree and inversion combination, causing missed opportunities for optimal solutions.
- error
Inadequate optimization that leads to a solution with higher than necessary time complexity, especially with large inputs.
进阶变体
外企场景- arrow_right_alt
Adjusting the number of allowed inversions, where a higher k requires better tracking of inversion effects.
- arrow_right_alt
Implementing the solution for a different tree structure or different constraints on the inversion operation count.
- arrow_right_alt
Optimizing further for extremely large trees or edge cases where n approaches the upper limit of 50,000 nodes.