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

力扣111二叉树的最小深度(DFS)

Problem: 111. 二叉树的最小深度

文章目录

  • 题目描述
  • 思路
  • 复杂度
  • Code

题目描述

在这里插入图片描述在这里插入图片描述

思路

1.欲望求出最短的路径,先可以记录一个变量minDepth,同时记录每次当前节点所在的层数currentDepth
2.在递的过程中,每次递一层,也即使当前又往下走了一层,则currentDepth++,当到达叶子节点时,比较并取出min【minDepth, currentDepth】
3.在归的过程中,因为是在往上层归,则currentDepth–;
4.返回最终的minDepth即可

复杂度

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为二叉树的节点个数

空间复杂度:

O ( h ) O(h) O(h);最坏空间复杂度

Code

DFS

/*** 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 {// record the minimum depth private int minDepth = Integer.MAX_VALUE;// record the depth of the current node being traversedprivate int currentDepth = 0;public int minDepth(TreeNode root) {if (root == null) {return 0;}// start DFS traverssal from the root nodetravers(root);return minDepth;}private void travers(TreeNode root) {if (root == null) {return;}// increase the current depth when entering a node in the preorder positioncurrentDepth++;// if the current node is a leaf, update the minimum depthif (root.left == null && root.right == null) {minDepth = Math.min(minDepth, currentDepth);}travers(root.left);travers(root.right);// decrease the current depth when leaving a node in the postorder positioncurrentDepth--;}
}
http://www.lryc.cn/news/527462.html

相关文章:

  • c++学习第十三天
  • zookeeper-3.8.3-基于ACL的访问控制
  • Java定时任务实现方案(四)——Spring Task
  • WGCLOUD运维工具从入门到精通 - 如何设置主题背景
  • Babylon.js 中的 setHardwareScalingLevel和getHardwareScalingLevel:作用与配合修改内容
  • Qwen2-VL:在任何分辨率下增强视觉语言模型对世界的感知 (大型视觉模型 核心技术 分享)
  • Docker——入门介绍
  • 02数组+字符串+滑动窗口+前缀和与差分+双指针(D2_字符串(D2_刷题练习))
  • 【redis进阶】集群 (Cluster)
  • Python案例--100到200的素数
  • C语言,无法正常释放char*的空间
  • 重回C语言之老兵重装上阵(十五)C语言错误处理
  • 基于微信的课堂助手小程序设计与实现(LW+源码+讲解)
  • Effective C++ 规则50:了解 new 和 delete 的合理替换时机
  • Alfresco Content Services dockerCompose自动化部署详尽操作
  • 学习第七十六行
  • YOLOv11改进,YOLOv11检测头融合DynamicHead,并添加小目标检测层(四头检测),适合目标检测、分割等任务
  • 一个基于Python+Appium的手机自动化项目~~
  • 【后端开发】字节跳动青训营之性能分析工具pprof
  • Linux:线程池和单例模式
  • 使用iis服务器模拟本地资源服务器unityaddressables热更新出错记录
  • TikTok广告投放优化策略:提升ROI的核心技巧
  • Hash表
  • 题解:P10972 I-Country
  • linux常用加固方式
  • 笔灵ai写作技术浅析(二):自然语言处理
  • PyCharm介绍
  • 深度解析:基于Vue 3与Element Plus的学校管理系统技术实现
  • Python从0到100(八十五):神经网络-使用迁移学习完成猫狗分类
  • 苍穹外卖 项目记录 day09 历史订单