二叉树的最小深度

http://www.lintcode.com/en/problem/minimum-depth-of-binary-tree/

注意点:见代码。  (根节点和其他节点是不同级别的结点,所以要分开考虑。其他节点左右为null则是叶结点,而根节点则还是根节点)

    如何剔除根节点和非叶子结点的影响,主函数里的root == null,是为了排除根节点;helper里的root == null,是为了排除其他非根节点的。(根节点和其他节点是不一样的结点。所以这两句代码都要写。)

    理逻辑的时候, 先 if(root.left == null && root.right == null) return 1; 

            后if(root == null) return Integer.MAX_VALUE;    

    写的时候两个顺序反过来,不然会报错。 

 1  public int minDepth(TreeNode root) {
 2     if(root == null) return 0;
 3     return helper(root);
 4  }
 5  private int helper(TreeNode root) {
 6      if(root == null) return Integer.MAX_VALUE;    
 7      if(root.left == null && root.right == null)  return 1;    
 8      //叶子节点,左右子树肯定都是null,所以除了这种情况,其它肯定不是叶子结点
 9      //所以假设左子非null,右子null,那右子树的结果肯定不能作为最终结果返回出来,要淘汰掉这个结果,就不妨设置这个结果为最大值,
10      //这样再下一次调用helper函数,传入为null的右子树时,会返回MAX_VALUE。
11      return Math.min(helper(root.left), helper(root.right)) + 1;
12  }
View Code     helper函数其实就是获取最小深度的函数
 1 public int minDepth(TreeNode root) {
 2     if(root == null) return 0;
 3     return    helper(root, 0);
 4 }
 5 private int helper(TreeNode root, int minDepth) {
 6     if(root == null) return Integer.MAX_VALUE;       //剔除非叶结点
 7     minDepth++;
 8     if(root.left == null && root.right == null) {    //叶结点
 9         return minDepth;
10     }
11     int right = helper(root.right, minDepth);
12     int left = helper(root.left,minDepth);
13     return Math.min(left,right);
14 }
5.11
原文地址:https://www.cnblogs.com/ddcckkk/p/6824616.html