LeetCode 题解工作台

标记所有节点需要的时间

给你一棵 无向 树,树中节点从 0 到 n - 1 编号。同时给你一个长度为 n - 1 的二维整数数组 edges ,其中 edges[i] = [u i , v i ] 表示节点 u i 和 v i 在树中有一条边。 一开始, 所有 节点都 未标记 。对于节点 i : 当 i 是奇数时,如果时刻…

category

4

题型

code_blocks

0

代码语言

hub

3

相关题

当前训练重点

困难 · 图·DFS·traversal

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 图·DFS·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一棵 无向 树,树中节点从 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 被标记。
  • 对于 i = 1 :
    • 节点 0 在时刻 t = 2 被标记,节点 2 在时刻 t = 4 被标记。
  • 对于 i = 2 :
    • 节点 0 在时刻 t = 2 被标记,节点 1 在时刻 t = 3 被标记。

示例 2:

输入:edges = [[0,1]]

输出:[1,2]

解释:

  • 对于 i = 0 :
    • 节点 1 在时刻 t = 1 被标记。
  • 对于 i = 1 :
    • 节点 0 在时刻 t = 2 被标记。

示例 3:

输入:edges = [[2,4],[0,1],[2,3],[0,2]]

输出:[4,6,3,5,5]

解释:

 

提示:

  • 2 <= n <= 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 <= edges[i][0], edges[i][1] <= n - 1
  • 输入保证 edges 表示一棵合法的树。
lightbulb

解题思路

方法一

1
2

speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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?

help

常见问题

外企场景

标记所有节点需要的时间题解:图·DFS·traversal | LeetCode #3241 困难