当前位置: 首页 > news >正文

LeetCode:二叉树的最大深度

1、题目描述

给定一个二叉树 root ,返回其最大深度。

二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:3

示例 2:

输入:root = [1,null,2]
输出:2

提示:

  • 树中节点的数量在 [0, 104] 区间内。

  • -100 <= Node.val <= 100

2、方法:递归法(深度优先DFS)

解题思路

递归法通过分解问题为子问题求解,分别计算左右子树的最大深度,再取较大值加 1(当前节点)。

步骤:

  1. 终止条件:当前节点为 null 时,深度为 0。

  2. 递归计算

    • 计算左子树的最大深度 leftDepth

    • 计算右子树的最大深度 rightDepth

  3. 返回结果max(leftDepth, rightDepth) + 1

时间复杂度:O(n),空间复杂度:O(n) (调用栈)

public int maxDepth(TreeNode root) {if (root == null) return 0;  // 终止条件int leftDepth = maxDepth(root.left);   // 递归左子树int rightDepth = maxDepth(root.right); // 递归右子树return Math.max(leftDepth, rightDepth) + 1; // 当前节点深度
}

3、方法2:迭代法(广度优先BFS)

解题思路

迭代法通过队列按层遍历节点,每遍历完一层,深度加 1。

步骤:

  1. 初始化:根节点入队,初始化深度 depth = 0

  2. 按层遍历

    • 记录当前层的节点数 size

    • 弹出 size 个节点,并将它们的子节点入队。

    • 每处理完一层,depth++

  3. 返回结果:队列为空时返回 depth

时间复杂度:O(n),空间复杂度:O(n) (栈空间)

public int maxDepth(TreeNode root) {if (root == null) return 0;Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);int depth = 0;while (!queue.isEmpty()) {int size = queue.size();  // 当前层的节点数while (size-- > 0) {      // 处理当前层所有节点TreeNode currNode = queue.poll();if (currNode.left != null) queue.offer(currNode.left);if (currNode.right != null) queue.offer(currNode.right);}depth++;  // 层数增加}return depth;
}

http://www.dtcms.com/a/176326.html

相关文章:

  • 基于DR模式的LVS集群案例
  • oracle 触发器与commit的先后执行顺序
  • Linux如何安装AppImage程序
  • Postman中https和http的区别是什么?
  • 2025数字中国创新大赛-数字安全赛道数据安全产业积分争夺赛决赛Writeup
  • fedora系统详解详细版本
  • 信息系统项目管理师-软考高级(软考高项)​​​​​​​​​​​2025最新(十)
  • 初学Python爬虫
  • 架设手游使用游戏盾SDK怎么提升网络速度?
  • 音频相关基础知识
  • RTC实时时钟DS1337S/PT7C4337WEX国产替代FRTC1337S
  • webRtc之指定摄像头设备绿屏问题
  • Ubuntu 单机多卡部署脚本: vLLM + DeepSeek 70B
  • 游戏引擎学习第262天:绘制多帧性能分析图
  • MySQL的深度分页如何优化?
  • ESP32开发入门(五):WiFi 开发实践
  • 0509滴滴前端项目常见内容
  • ElementUI 表格el-table自适应高度设置
  • 007 Linux 开发工具(上)—— vim、解放sudo、gc+
  • Golang 接口 vs Rust Trait:一场关于抽象的哲学对话
  • LeetCode383_赎金信
  • Jenkins 服务器上安装 Git
  • Apache Calcite 详细介绍
  • 【EasyPan】loadDataList方法及checkRootFilePid方法解析
  • comfyui 实现中文提示词翻译英文进行图像生成
  • VScode一直处于循环“正在重新激活终端“问题的解决方法
  • 【上位机——MFC】序列化机制
  • 机器学习在信用卡欺诈检测中的应用思考
  • 基于英特尔 RealSense D455 结构光相机实现裂缝尺寸以及深度测量
  • svn服务器迁移