leetcode(31).111. Minimum Depth of Binary Tree
来源:互联网 发布:orange作图软件中文版 编辑:程序博客网 时间:2024/05/17 07:31
题意:给定一个二叉树,查找其最小深度。
初步分析:递归的获取到最小深度。(从上往下,左右子树深度相比,每次递归都取最小的那个再加1)
public class Solution { public int minDepth(TreeNode root) { if(root == null) return 0; return Math.min(minDepth(root.left),minDepth(root.right))+1; }}但是,这样有错
左右子树有一个为空的时候,那么min就直接就是0了(不管另一个子树有多高)
也就是说不管是
* 还是 *
*
高度都是1,显然是不对的。
比如:
a
b
返回1.但应该是2,因为结点b的高度为1(min(0,0)+1),但是a的高度为(min(b,0)+1)即(min(1,0)+1)即1.
我们发现,左结点或者右结点有一者不为空的时候,取小的时候会直接抹掉另一个子树的高度。
所以这种情况应该直接取不为空那一边子树的高度(再加1)
深度优先搜索:
/** * 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; int dep = 0; if(root.left!=null && root.right!=null) dep = Math.min(minDepth(root.left),minDepth(root.right)); if(root.left == null) //左子树为空,右子树不为空,取右子树的高度 dep = minDepth(root.right); if(root.right == null) //右子树为空。左子树不为空,取左子树的高度 dep = minDepth(root.left); return dep+1; }}
广度优先搜索(将每一层不是叶子结点的放入层次遍历队列中,每次取出一层,每遍历一层高度加一,直到遇到叶子节点为止):
public int minDepth(TreeNode root) { if (root == null) { return 0; } Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int depth = 1; //按层记高度,根节点是第一层,高度为一 while (!queue.isEmpty()) { int l = queue.size(); for (int i = 0; i < l; i++) { TreeNode n = queue.poll(); //取出当前层所有结点 if (n.left == null && n.right == null) { //到叶子节点就返回高度 return depth; } if (n.left != null) { //将不为空的结点放入下一层(只要不是叶子节点(左右都为空)就要继续计数) queue.add(n.left); } if (n.right != null) { queue.add(n.right); } } depth++; //每一层,高度加一 } return depth;}
0 0
- LeetCode 111. Minimum Depth of Binary Tree
- [LeetCode]111.Minimum Depth of Binary Tree
- 【LeetCode】111.Minimum Depth of Binary Tree
- [Leetcode] 111. Minimum Depth of Binary Tree
- [leetcode] 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree LeetCode
- 【LeetCode】111. Minimum Depth of Binary Tree
- LeetCode *** 111. Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- leetcode-111. Minimum Depth of Binary Tree
- LeetCode-111.Minimum Depth of Binary Tree
- LeetCode 111.Minimum Depth of Binary Tree
- Leetcode 111. Minimum Depth of Binary Tree
- [leetcode]111.Minimum Depth of Binary Tree
- 111.[Leetcode]Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- 【leetcode】111. Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- #早安,努力#11.23
- 终结者:HTTPS在Tomcat中的使用(一)——生成密钥库文件与配置Tomcat服务器
- Hadoop、Spark等5种大数据框架对比,你的项目该用哪种?
- Android中Application组件的基础用法。
- Hadoop中hdfs的操作:
- leetcode(31).111. Minimum Depth of Binary Tree
- #DeepLearningBook#算法概览之五:Sequence Modeling
- iOS 10 不提示「是否允许应用访问数据」,导致应用无法使用的解决方案
- Java面向对象之封装
- Oracle中查找没有主键的表
- Spring学习历程---Hibernate访问数据库可脱离事务管理器
- [李景山php]每天TP5-20161228|thinkphp5-Console.php-5
- IOS两张图片合成为一张图片
- 在Linux系统下搭建Samba共享服务器的详细步骤