题目

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;
     }

最新文章

  1. 极路由2(极贰)在OpenWrt下定制自己的ss服务
  2. php session的操作
  3. iOS各种调试技巧豪华套餐
  4. erl_0011 erlang 定时器相关
  5. UVA 10600 ACM Contest and Blackout 次小生成树
  6. 【HDOJ】1332 LC-Display
  7. css实现两端对齐的3种方法
  8. zookeeper 分布式应用好处
  9. 开源纯C#工控网关+组态软件(六)图元组件
  10. WebApiClient库支持AOT
  11. git window安装与注册邮箱用户名
  12. 彻底删除mysql服务(清理注册表)
  13. deepin使用笔记-解决蓝牙设备开机自动开启的问题
  14. BD是什么角色
  15. 7:servlet request getHeader(&quot;x-forwarded-for&quot;) 获取真实IP
  16. Java heap space cdh 5.11.1
  17. ios开发之--AVAudioPlayer/AVPlayer的应用
  18. Python模拟登录的几种方法
  19. [洛谷P3292] [SCOI2016]幸运数字
  20. Docker 安装使用

热门文章

  1. Top 5 SSH Clients for Windows (Alternatives of PuTTY)
  2. Mac 上自带TFTP Server 软件的使用
  3. iOS 11开发教程(十二)iOS11应用视图始祖——UIView
  4. Mysql表连接查询
  5. 机器学习之路:python 网格搜索 并行搜索 GridSearchCV 模型检验方法
  6. 【UOJ #221】【NOI 2016】循环之美
  7. BZOJ.2339.[HNOI2011]卡农(思路 DP 组合 容斥)
  8. mysql数据库cup飙升处理思路
  9. generator自动生成mybatis的xml配置
  10. PostgreSQL 资料库