LeetCode:2385. 感染二叉树需要的总时间(DFS Java)

目录

[2385. 感染二叉树需要的总时间](#2385. 感染二叉树需要的总时间)

题目描述:

实现代码与解析:

DFS

原理思路:


2385. 感染二叉树需要的总时间

题目描述:

给你一棵二叉树的根节点 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 的节点

实现代码与解析:

DFS

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    Map<TreeNode, TreeNode> map = new HashMap<>();
    TreeNode startNode;

    public int amountOfTime(TreeNode root, int start) {

        dfs(root, null, start);
        int res = getMaxDepth(startNode, startNode);
        return res - 1;
    }

    private int getMaxDepth(TreeNode cur, TreeNode from) {

        if (cur == null) return 0;
        int res = -1;

        if (cur.left != from) res = Math.max(res, getMaxDepth(cur.left, cur));
        if (cur.right != from) res = Math.max(res, getMaxDepth(cur.right, cur));
        if (map.get(cur) != from) res = Math.max(res, getMaxDepth(map.get(cur) , cur));

        return res + 1;
    }

    public void dfs(TreeNode cur, TreeNode fa, int start) {

        if (fa != null)  map.put(cur, fa);

        if (cur.val == start) startNode = cur;
        if (cur.left != null) dfs(cur.left, cur, start);
        if (cur.right != null) dfs(cur.right, cur, start);
    }
}

原理思路:

根据题意,显然是需要我们从start开始遍历即可,但是这是二叉树,无法从子节点到叶子节点,所以先dfs把每个节点父节点进行记录,这样就可以从子节点移动到父节点。

然后从start开始遍历即可,不要重复遍历,所以记录from,这里可以bfs层次求深度,也可以dfs求最大深度。

因为第0分钟就已经感染start了,所以res-1是答案。

相关推荐
AI备案指南-满满1 小时前
人工智能拟人化互动服务安全自评估报告的评估要点有哪些?
人工智能·算法·安全·机器人·大模型备案·算法备案
土司大王3 小时前
LeetCode hot100——两两交换链表中的节点
算法·leetcode·职场和发展
大熊背4 小时前
树莓派IspPipeline LSC模块原理详解
算法·lsc·isppipeline·mesh lsc
zander2584 小时前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
欧叶冲冲冲5 小时前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
祖力555 小时前
Linux应用软件编程:目录IO与framebuffer
linux·运维·算法·framebuffer·目录io
名字还没想好☜5 小时前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
地平线开发者5 小时前
【模型轻量化专题】深度学习模型为什么需要轻量化
算法
圣保罗的大教堂5 小时前
leetcode 3622. 判断整除性 简单
leetcode