查找二叉树的最小深度

来源:互联网 发布:淘宝没给发票 编辑:程序博客网 时间:2024/06/06 05:31

题目: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

代码:

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


1 0
原创粉丝点击