Minimum Depth of Binary Tree leetcode java
2024-08-21 17:24:37
题目:
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
题解:
递归解法急速判断左右两边子树哪个depth最小,要注意如果有个节点只有一边孩子时,不能返回0,要返回另外一半边的depth。
递归解法:
public int minDepth(TreeNode root) {
if(root == null)
return 0;
int minleft = minDepth(root.left);
int minright = minDepth(root.right);
if(minleft==0 || minright==0)
return minleft>=minright?minleft+1:minright+1;
return Math.min(minleft,minright)+1;
}
非递归解法:
1 public int minDepth(TreeNode root) {
2 if(root == null)
3 return 0;
4
5 int depth = 1;//The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
6 LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
7 queue.add(root);
8 int curnum = 1;
9 int nextnum = 0;
while(!queue.isEmpty()){
TreeNode cur = queue.poll();
curnum--;
if(cur.left == null && cur.right == null)
return depth;
if(cur.left != null){
queue.add(cur.left);
nextnum++;
}
if(cur.right != null){
queue.add(cur.right);
nextnum++;
}
if(curnum == 0){
curnum = nextnum;
nextnum = 0;
depth++;
}
}
return depth;
}
最新文章
- 极路由2(极贰)在OpenWrt下定制自己的ss服务
- php session的操作
- iOS各种调试技巧豪华套餐
- erl_0011 erlang 定时器相关
- UVA 10600 ACM Contest and Blackout 次小生成树
- 【HDOJ】1332 LC-Display
- css实现两端对齐的3种方法
- zookeeper 分布式应用好处
- 开源纯C#工控网关+组态软件(六)图元组件
- WebApiClient库支持AOT
- git window安装与注册邮箱用户名
- 彻底删除mysql服务(清理注册表)
- deepin使用笔记-解决蓝牙设备开机自动开启的问题
- BD是什么角色
- 7:servlet request getHeader(";x-forwarded-for";) 获取真实IP
- Java heap space cdh 5.11.1
- ios开发之--AVAudioPlayer/AVPlayer的应用
- Python模拟登录的几种方法
- [洛谷P3292] [SCOI2016]幸运数字
- Docker 安装使用
热门文章
- Top 5 SSH Clients for Windows (Alternatives of PuTTY)
- Mac 上自带TFTP Server 软件的使用
- iOS 11开发教程(十二)iOS11应用视图始祖——UIView
- Mysql表连接查询
- 机器学习之路:python 网格搜索 并行搜索 GridSearchCV 模型检验方法
- 【UOJ #221】【NOI 2016】循环之美
- BZOJ.2339.[HNOI2011]卡农(思路 DP 组合 容斥)
- mysql数据库cup飙升处理思路
- generator自动生成mybatis的xml配置
- PostgreSQL 资料库