Minimum Depth of Binary Tree 二叉树最小深度

//运用递归的思想,当节点为空时间,即1 2 V 3 V V V 。当左子树为空时,及左子树在具象图上面根本不存在,此时root的深度等于右子树的深度+1;反之亦然

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
          return minRec(root);  
    }  
      
    private int minRec(TreeNode root) {  
        if(root==null) return 0;  
          
        int l = minRec(root.left);  
        int r = minRec(root.right);  
          
        if(l==0) return r+1;  
        if(r==0) return l+1;  
          
        return Math.min(l, r) + 1;  
          
    }  
}  
//也可以从另一方面想,就是当节点为空时间,判断右子树是否存在,当存在时,此节点深度为正无穷(INT_MAX);若不存在,则此节点深度为0
public class MinimumDepthofBinaryTree {
      public int minDepth(TreeNode root) {
          if (root == null)
              return 0;
          if (root.left == null && root.right == null)
             return 1;
         else {
             int leftDepth = root.left != null ? minDepth(root.left)
                     : Integer.MAX_VALUE;
             int rightDepth = root.right != null ? minDepth(root.right)
                     : Integer.MAX_VALUE;
             return Math.min(leftDepth,rightDepth) + 1;
         }
     }
}

就比如说这样

int minDepth(TreeNode *root) {  
        // Start typing your C/C++ solution below  
        // DO NOT write int main() function  
        if(root == NULL)  
        {  
            return 0;  
        }  
        else  
        {  
            minD(root);  
        }  
    }  
      
    int minD(TreeNode *root) {  
        if(root->left == NULL && root->right == NULL)  
        {  
            return 1;  
        }  
        else  
        {  
            if(root->left == NULL)  
            {  
                return minD(root->right) + 1;  
            }  
            else if(root->right == NULL)  
            {  
                return minD(root->left) + 1;  
            }  
            else  
            {  
                int left = minD(root->left);  
                int right = minD(root->right);  
                return (left<right?left:right) + 1;  
            }  
        }  
    }  
};  




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值