Day16_BT, Leetcode 104, 111, and 222

Leetcode 104:

https://leetcode.com/problems/maximum-depth-of-binary-tree/

题目的第一想法:

这道题的解法其实很容易,就是只要看最大值就好。所以用1+max(left,right)就好。

class Solution {
    public int maxDepth(TreeNode root) {  
        return root != null ? 1 + Math.max(maxDepth(root.left), maxDepth(root.right)): 0;
    }
}

Leetcode 111:

https://leetcode.com/problems/minimum-depth-of-binary-tree/

题目的第一想法:

这道题的解法和上一道求最深node的题看似一样但需要考虑更深一层。考虑一个只有一边的node,如果只求最小值那么算法必然会走到null(因为null总为0)然后返回。如此算法就会在树的中间停止,不会返回正确答案。所以我们需要做的是把情况再次细分,有两个base case和三个recurssive condition。两个base case为当node是leaf或当node为null。三个reucrssive condition是当node左边存在branch右边不存在(往左继续计算),当node右边存在左边不存在(往右继续计算)和当node左右两边都存在(取最小值)。

class Solution {
    public int minDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        if(isLeaf(root)){return 1;}
        else if(root.left == null && root.right != null){
            return 1 + minDepth(root.right);
        }else if(root.right == null && root.left != null){
            return 1 + minDepth(root.left);
        }else{
            return 1 + Math.min(minDepth(root.left), minDepth(root.right));
        }
    }

    public boolean isLeaf(TreeNode root){
        return root.left == null && root.right == null;
    }
}

Leetcode 222:

https://leetcode.com/problems/count-complete-tree-nodes/description/

题目的第一想法:

这道题从难度上来看感觉不够medium的难度。基本的思路是如果是一个leaf就算1,如果是null就是0,如果是任意其他情况就recurrsion下去,关系是1+左边的数字和右边的数字。

class Solution {
    public int countNodes(TreeNode root) {
        if(root == null){
            return 0;
        }else if(root.left == null && root.right == null){
            return 1;
        }else{
            return 1 + countNodes(root.left) + countNodes(root.right);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值