查找二叉树的最小深度
2016-09-14 09:28
316 查看
题目:Minimum-depth-of-binary-tree
要求: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.
分析:①、使用递归,相当于遍历了整个二叉树,递归返回深度浅的那棵子树的深度。
②、按层检查有没有叶子节点,有的话停止检查,返回当前层数。至于实现这个按层检查,可以用递归的方法。该法不用遍历整个树。
遍历分类:1、当根节点为空时,返回0
2、当只有左子节点(无右子节点)时,返回 1
3、当只有右子节点(无左子节点)时,返回 1
4、当左右子节点都存在时,分别计算左子树和右子树的深度,min(左子树最小深度,右子树最小深度)+1
代码:
1、当根为空时,输出0
2、当左子树为空时,输出右子树深度+1
3、当右子树为空时,输出左子树深度+1
4、以上条件都不满足时,输出min(左子树深度,右子树深度)+1
要求: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.
分析:①、使用递归,相当于遍历了整个二叉树,递归返回深度浅的那棵子树的深度。
②、按层检查有没有叶子节点,有的话停止检查,返回当前层数。至于实现这个按层检查,可以用递归的方法。该法不用遍历整个树。
遍历分类:1、当根节点为空时,返回0
2、当只有左子节点(无右子节点)时,返回 1
3、当只有右子节点(无左子节点)时,返回 1
4、当左右子节点都存在时,分别计算左子树和右子树的深度,min(左子树最小深度,右子树最小深度)+1
代码:
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { public int run(TreeNode root) { if(root!=null){ int left = Integer.MAX_VALUE; int right = Integer.MAX_VALUE; if(root.left!=null){ left = run(root.left); } if(root.right!=null){ right = run(root.right); } if(left<right){ return left+1; } else if(left>right){ return right+1; } else if(left==right&&left!=Integer.MAX_VALUE){ return left+1; } else return 1; } return 0; } }其实,递归的核心在于,从根节点找到最近的叶节点,所以,递归又可以改为:
1、当根为空时,输出0
2、当左子树为空时,输出右子树深度+1
3、当右子树为空时,输出左子树深度+1
4、以上条件都不满足时,输出min(左子树深度,右子树深度)+1
public class Solution { public int run(TreeNode root) { if(root==null) return 0; if(root.left==null) return run(root.right)+1; if(root.right==null) return run(root.left)+1; return Math.min(run(root.left),run(root.right))+1; } }
相关文章推荐
- 二叉树的最小深度
- 二叉树的最小深度
- LeetCode—二叉树的最大最小深度
- 111. Minimum Depth of Binary Tree 二叉树的最小深度
- 二叉树的中序、先序、后序、层序遍历 & 二叉树的深度 & 节点查找
- LeetCode 二叉树的最小深度
- 二叉树最小深度
- lintcode minimum-depth-of-binary-tree 二叉树最小深度
- [Java代码] [Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度
- 二叉树的最小深度
- 二叉树的查找,插入,删除,遍历,最小值,最大值 操作
- 二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- lintcode ----二叉树的最小深度
- 二叉树的最大深度与最小深度
- LintCode:二叉树的最小深度
- [Leetcode] The minimum depth of binary tree二叉树的最小深度
- lintcode-155-二叉树的最小深度
- 二叉树的最小深度
- 【leetcode】Minimum Depth of Binary Tree 二叉树的最小深度 (JAVA)
- 二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现