小白刷leetcode——二叉树(104. 二叉树的最大深度、111.二叉树的最小深度、222.完全二叉树的节点个数)

104. 二叉树的最大深度
两种方式:1.求二叉树的高度  2.求二叉树的深度
本次用的是方法1,即通过求二叉树的高度得出结果,因为二叉树高度=深度
思路:
    因为求二叉树高度需要遍历到最深层,然后一层一层返回并+1,因此需要用到后序遍历,类似于昨天的101. 对称二叉树,都是需要对节点的左右孩子情况判断结束后,再向上一层一层的返回结果。
    也可以理解为从根节点出发,用1+max(左、右节点高度),然后一层一层向下遍历,分别求出每层节点左右孩子的最大高度然后再return +1
    类似于101.对称二叉树,利用后序遍历,都是先递归判断左右孩子情况,然后再return处理中间节点
class Solution {
    public int maxDepth(TreeNode root) {
        if(root ==null) return 0;
        return getDepth(root);
    }
    public int getDepth(TreeNode root){
        if(root == null) return 0;
        int leftDepth = getDepth(root.left);
        int rightDepth = getDepth(root.right);
        return Math.max(leftDepth,rightDepth) + 1;
    }
}

111.二叉树的最小深度

思路:(递归法和迭代法两种方法)
    层序遍历法更容易理解
    层序遍历模板差不多,在向队列插入头结点后,进入while循环,此时定义size用来记录当前层个数,内层循环每结束一次,都是代表进入二叉树的下一层。在内层循环,每弹出一个元素都要判断一下当前元素是否是叶子节点(没有孩子),如果是直接返回结果。如果不是继续添加孩子
class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int res = 0;
        while (!queue.isEmpty()){
            
            int size = queue.size();
            res ++;
            while(size-- > 0){
                TreeNode node = queue.poll();//当队列内当前层size不为空时,弹出当前层队列头元素
                if(node.left ==  null && node.right == null) return res;
                if(node.left != null) queue.offer(node.left);
                if(node.right != null) queue.offer(node.right);
            }
        }
        return res;
    }
}

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

​思路:
    利用层序遍历,循环弹出队列元素,同时使用res++计数
递归:
public int countNodes(TreeNode root){
    if(root == null) return 0;
    int countLeft = countNodes(root.left);
    int countRight = countNodes(root.right);
    return countLeft + countRight +1 ;
}
迭代:
public int countNodes(TreeNode root){
    if(root == null ) return 0;
    Queue<TreeNode> queue = new LinkedList<>();
    int res = 0;
    queue.offer(root);
    while(!queue.isEmpty()){
        int size = queue.size();
        while(size -- > 0){
        TreeNode node = queue.poll();
        res++;
        if(node.left != null) queue.offer(node.left);
        if(node.right != null) queue.offer(node.right);
        }
    }return res;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小刘成长日记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值