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

二叉树的深度

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

一、最大深度

104. 二叉树的最大深度 - 力扣(LeetCode)

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

//递归法
/*** 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 {public int maxDepth(TreeNode root) {return getdepth(root);}public int getdepth(TreeNode root){if(root==null)return 0;int rdepth=getdepth(root.right);int ldepth=getdepth(root.left);int depth=Math.max(rdepth,ldepth)+1;return depth;}
}

二、最小深度

111. 二叉树的最小深度 - 力扣(LeetCode)

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

//递归法
/*** 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 {public int minDepth(TreeNode root) {return getdepth(root);}public int getdepth(TreeNode root){if(root==null)return 0;int rdepth=getdepth(root.right);int ldepth=getdepth(root.left);if(root.left==null&&root.right!=null)return rdepth+1;//左为空,右不为空,说明此时不是最近叶子结点if(root.left!=null&&root.right==null)return ldepth+1;//左不为空,右为空,说明此时不是最近叶子结点int depth=Math.min(rdepth,ldepth)+1;return depth;}
}

相关文章:

  • Conda激活环境无效
  • 对称加密以及非对称加密
  • transformer 笔记 tokenizer moe
  • [Windows] 希捷(Seagate)硬盘官方检测工具 - SeaTools(1.4.0.7)
  • 【身份证识别表格】批量识别身份证扫描件或照片保存为Excel表格,怎么大批量将身份证图片转为excel表格?基于WPF和腾讯OCR的识别方案
  • Path to Integer_ABC402分析与解答
  • SCDN是什么?
  • 上班摸鱼远程打游戏,哪款远控软件好用点?
  • 【Bootstrap V4系列】学习入门教程之 组件-表单(Forms)
  • MySQL如何优雅的执行DDL
  • 图解gpt之神经概率语言模型与循环神经网络
  • 【应急响应】- 日志流量如何分析?
  • SecureCRT网络穿透/代理
  • 网络研讨会开发注册中, 5月15日特励达力科,“了解以太网”
  • 深入理解C/C++内存管理:从基础到高级优化实践
  • kafka 面试总结
  • 微服务中 本地启动 springboot 无法找到nacos配置 启动报错
  • Mac QT水平布局和垂直布局
  • 怎么用idea打jar包
  • 【从0带做】基于Springboot3+Vue3的文物展览系统
  • 105岁八路军老战士、抗美援朝老战士谭克煜逝世
  • Meta正为AI眼镜开发人脸识别功能
  • 4月深圳新房、二手房成交同比均上涨,“5月有望延续积极向好的发展态势”
  • 长安汽车辟谣作为二级企业并入东风集团:将追究相关方责任
  • 吴清:加强监管的同时传递监管温度,尽力帮助受影响企业应对美加征关税的冲击
  • 市场监管总局发布《城镇房屋租赁合同(示范文本)》