Minimum Depth of Binary Tree
来源:互联网 发布:腾讯微信数据库多大 编辑:程序博客网 时间:2024/06/11 00:14
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.
一开始的考虑很有问题,忘了考虑是到结点(左右子树都为空)的路径,所以就有了下面的代码:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int minDepth(TreeNode root) { if(root==null) return 0; return Math.min(minDepth(root.left),minDepth(root.right))+1; }}很显然,以上代码如果跑
2
1
得到的结果是1;
但是实际上应该是为2.。
修正后代码如下:添加了左子树为空,和 右子树为空的情况。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int minDepth(TreeNode root) { if(root==null) return 0; if(root.left==null) return minDepth(root.right)+1; if(root.right ==null) return minDepth(root.left)+1; return Math.min(minDepth(root.left),minDepth(root.right))+1; }}
0 0
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- SpringJPA(Hibernate) 处理基于基类的关联关系
- Android进阶_WebView与JS进行交互
- zookeeper源码分析----节点创建流程
- CCClipingNode的使用
- Spring Boot 学习第三步(Spring Data JPA学习汇总)
- Minimum Depth of Binary Tree
- java去除字符串中的空格、回车、换行符、制表符
- selenium面试题
- Git 菜鸟变大神(二) 如何提交文件和历史版本恢复
- lcd驱动。。解决开发板小企鹅logo跑偏问题
- Resharper的使用
- 欢迎使用CSDN-markdown编辑器
- SecureCRT下如何解决vi背景色的问题
- JDBC-获取Connection对象