LeetCode 题解工作台
标记所有节点需要的时间
给你一棵 无向 树,树中节点从 0 到 n - 1 编号。同时给你一个长度为 n - 1 的二维整数数组 edges ,其中 edges[i] = [u i , v i ] 表示节点 u i 和 v i 在树中有一条边。 一开始, 所有 节点都 未标记 。对于节点 i : 当 i 是奇数时,如果时刻…
4
题型
0
代码语言
3
相关题
当前训练重点
困难 · 图·DFS·traversal
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 图·DFS·traversal 题型思路
题目描述
给你一棵 无向 树,树中节点从 0 到 n - 1 编号。同时给你一个长度为 n - 1 的二维整数数组 edges ,其中 edges[i] = [ui, vi] 表示节点 ui 和 vi 在树中有一条边。
一开始,所有 节点都 未标记 。对于节点 i :
- 当
i是奇数时,如果时刻x - 1该节点有 至少 一个相邻节点已经被标记了,那么节点i会在时刻x被标记。 - 当
i是偶数时,如果时刻x - 2该节点有 至少 一个相邻节点已经被标记了,那么节点i会在时刻x被标记。
请你返回一个数组 times ,表示如果你在时刻 t = 0 标记节点 i ,那么时刻 times[i] 时,树中所有节点都会被标记。
请注意,每个 times[i] 的答案都是独立的,即当你标记节点 i 时,所有其他节点都未标记。
示例 1:
输入:edges = [[0,1],[0,2]]
输出:[2,4,3]
解释:

- 对于
i = 0:- 节点 1 在时刻
t = 1被标记,节点 2 在时刻t = 2被标记。
- 节点 1 在时刻
- 对于
i = 1:- 节点 0 在时刻
t = 2被标记,节点 2 在时刻t = 4被标记。
- 节点 0 在时刻
- 对于
i = 2:- 节点 0 在时刻
t = 2被标记,节点 1 在时刻t = 3被标记。
- 节点 0 在时刻
示例 2:
输入:edges = [[0,1]]
输出:[1,2]
解释:

- 对于
i = 0:- 节点 1 在时刻
t = 1被标记。
- 节点 1 在时刻
- 对于
i = 1:- 节点 0 在时刻
t = 2被标记。
- 节点 0 在时刻
示例 3:
输入:edges = [[2,4],[0,1],[2,3],[0,2]]
输出:[4,6,3,5,5]
解释:

提示:
2 <= n <= 105edges.length == n - 1edges[i].length == 20 <= edges[i][0], edges[i][1] <= n - 1- 输入保证
edges表示一棵合法的树。
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidates should understand tree traversal techniques and be able to optimize with dynamic programming.
- question_mark
Look for an approach that minimizes redundant calculations in tree traversal.
- question_mark
Expect candidates to consider edge cases and tree sizes up to n = 10^5.
常见陷阱
外企场景- error
Not optimizing the DFS traversal using dynamic programming, resulting in recalculating times for the same nodes.
- error
Misunderstanding the propagation of times when transitioning from one subtree to another.
- error
Overcomplicating the problem by attempting a brute-force solution rather than leveraging DFS and dynamic programming.
进阶变体
外企场景- arrow_right_alt
What happens if the tree is unbalanced? How does the approach scale?
- arrow_right_alt
Can this approach be adapted to handle multiple starting nodes simultaneously?
- arrow_right_alt
How would the solution change if nodes could be marked at times other than t=0?