LeetCode 题解工作台

感染二叉树需要的总时间

给你一棵二叉树的根节点 root ,二叉树中节点的值 互不相同 。另给你一个整数 start 。在第 0 分钟, 感染 将会从值为 start 的节点开始爆发。 每分钟,如果节点满足以下全部条件,就会被感染: 节点此前还没有感染。 节点与一个已感染节点相邻。 返回感染整棵树需要的分钟数 。 示例 1…

category

5

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·树·traversal

bolt

答案摘要

我们先通过一次 建图,得到一个邻接表 ,其中 表示与节点 相连的所有节点。 然后,我们以 作为起点,通过 搜索整棵树,找到最远距离,即为答案。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一棵二叉树的根节点 root ,二叉树中节点的值 互不相同 。另给你一个整数 start 。在第 0 分钟,感染 将会从值为 start 的节点开始爆发。

每分钟,如果节点满足以下全部条件,就会被感染:

  • 节点此前还没有感染。
  • 节点与一个已感染节点相邻。

返回感染整棵树需要的分钟数

 

示例 1:

输入:root = [1,5,3,null,4,10,6,9,2], start = 3
输出:4
解释:节点按以下过程被感染:
- 第 0 分钟:节点 3
- 第 1 分钟:节点 1、10、6
- 第 2 分钟:节点5
- 第 3 分钟:节点 4
- 第 4 分钟:节点 9 和 2
感染整棵树需要 4 分钟,所以返回 4 。

示例 2:

输入:root = [1], start = 1
输出:0
解释:第 0 分钟,树中唯一一个节点处于感染状态,返回 0 。

 

提示:

  • 树中节点的数目在范围 [1, 105]
  • 1 <= Node.val <= 105
  • 每个节点的值 互不相同
  • 树中必定存在值为 start 的节点
lightbulb

解题思路

方法一:两次 DFS

我们先通过一次 DFS\textit{DFS} 建图,得到一个邻接表 gg,其中 g[node]g[node] 表示与节点 nodenode 相连的所有节点。

然后,我们以 startstart 作为起点,通过 DFS\textit{DFS} 搜索整棵树,找到最远距离,即为答案。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为二叉树的节点个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
        def dfs(node: Optional[TreeNode], fa: Optional[TreeNode]):
            if node is None:
                return
            if fa:
                g[node.val].append(fa.val)
                g[fa.val].append(node.val)
            dfs(node.left, node)
            dfs(node.right, node)

        def dfs2(node: int, fa: int) -> int:
            ans = 0
            for nxt in g[node]:
                if nxt != fa:
                    ans = max(ans, 1 + dfs2(nxt, node))
            return ans

        g = defaultdict(list)
        dfs(root, None)
        return dfs2(start, -1)
speed

复杂度分析

指标
时间O(n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    The problem tests the ability to convert a tree into an undirected graph.

  • question_mark

    The candidate demonstrates understanding of BFS/DFS and state management in tree-like structures.

  • question_mark

    The solution should involve careful handling of state to avoid redundant infections.

warning

常见陷阱

外企场景
  • error

    Failing to convert the tree into an undirected graph before starting traversal can lead to incorrect infection spread handling.

  • error

    Not keeping track of the visited nodes can cause infinite loops or re-infection of already infected nodes.

  • error

    Misunderstanding the BFS/DFS approach can lead to inefficient or incorrect spread simulation.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    The tree can be large with up to 105 nodes, requiring careful space and time optimization.

  • arrow_right_alt

    The infection might not be continuous; ensure each minute correctly tracks the new infections.

  • arrow_right_alt

    Edge cases where the tree consists of only one node or the infection starts at a leaf node should be handled.

help

常见问题

外企场景

感染二叉树需要的总时间题解:二分·树·traversal | LeetCode #2385 中等