day 16|● 104.二叉树的最大深度 559.n叉树的最大深度● 111.二叉树的最小深度● 222.完全二叉树的节点个数

● 104.二叉树的最大深度

必须首先确定遍历方式:

求二叉树的高度:因为求高度,就好像一座大楼在你面前,你肯定是从底层往楼顶去数,所以说呢,就是从底下往上走,那么只有后序遍历符合这个要求了,先左,再右,最后在中。

求二叉树的深度:你现在求深度,就好像你看一口井有多深,肯定是,从地面慢慢看到最深处,所以说呢,只有前序遍历符合该要求,先中,再左,再右。

一开始空结点返回值我写成1了。错了,现在直到应该是0了,还有left和right,每调用一次,就要+1,刚做这道题的时候我确实有点懵。这题因为是求最大深度,相当于高度,所以就用后序了。

class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null){
            return 0;空结点的高度是0,返回0     
        }
        int left = 1+maxDepth(root.left);
        int right = 1+maxDepth(root.right);
        return Math.max(left,right);
    }
}

559.n叉树的最大深度

没想明白,之后复习再看,

可能是每次运行,int depth=0只运行一次吧。

自己画一下图,你会发现,depth往往会出现再max函数里面,而且被比下去,因为在该层递归,它一直是0。

class Solution {

    public int maxDepth(Node root) {
        if(root == null){
            return 0;
        }
        int depth = 0;
        if(root.children != null){
            for(Node child:root.children){
                depth = Math.max(depth, maxDepth(child));
            }
        }
        return depth+1;
    }
}

● 111.二叉树的最小深度

是在求二叉树的最大深度的基础上,加了额外的限定条件。

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

● 222.完全二叉树的节点个数

普通二叉树写法

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

这是完全二叉树的写法,没太明白 

class Solution {
    public int countNodes(TreeNode root) {
        if(root == null){
            return 0;
        }
        TreeNode left = root.left;
        TreeNode right = root.right;
        int leftdepth = 0, rightdepth = 0;
        while(left!=null){
            left = left.left;
            leftdepth++;
        }
        while(right!=null){
            right = right.right;
            rightdepth++;
        }
        if(leftdepth==rightdepth){
            return (2<<leftdepth)-1;
        }
        int leftnum= countNodes(root.left);
        int rightnum = countNodes(root.right);
        return leftnum+rightnum+1;


    }
}

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值