二叉树3| 104.二叉树的最大深度|111.二叉树的最小深度|222.完全二叉树的节点个数

二叉树3| 104.二叉树的最大深度|111.二叉树的最小深度|222.完全二叉树的节点个数

一、104.二叉树的最大深度

题目连接:104. 二叉树的最大深度 - 力扣(LeetCode)

  1. 此题可采用前序遍历、后序遍历、层序遍历解决,后序遍历方法如下:
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        int lh = maxDepth(root.left);//左
        int rh = maxDepth(root.right);//右
        return Math.max(lh, rh) + 1;//中
    }
}

二、111.二叉树的最小深度

题目连接:111. 二叉树的最小深度 - 力扣(LeetCode)

  1. 注意:最小深度是从根节点到最近叶子节点的最短路径上的节点数量,叶子节点是指没有子节点的节点。取最小值的同时,注意会有左子树为空,右子树不为空的情况下应该取右子树的高度。
class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        int lh = minDepth(root.left);
        int rh = minDepth(root.right);
        if(root.left == null && root.right != null){
            return rh + 1;
        }
        if(root.left != null && root.right == null){
            return lh + 1;
        }
        return Math.min(lh, rh) + 1;
    }
}

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

题目连接:222. 完全二叉树的节点个数 - 力扣(LeetCode)

  1. 将其当成普通二叉树遍历节点,后序遍历
class Solution {
    public int countNodes(TreeNode root) {
        if(root == null) return 0;
        int left = countNodes(root.left);
        int right = countNodes(root.right);
        return left + right + 1;
    }
}
  1. 利用完全二叉树的性质解题,后序遍历。先判断子二叉树是否是满二叉树,若是则利用2^n - 1计算节点个数;若不是则继续向下遍历,判断其子树是否是,返回节点个数。
class Solution {
    public int countNodes(TreeNode root) {
        if(root == null) return 0;
        TreeNode left = root.left;
        TreeNode right = root.right;
        int lefedepth = 0;
        int rightdepth = 0;
        while(left != null){
            left = left.left;
            lefedepth++;
        }
        while (right != null){
            right = right.right;
            rightdepth++;
        }
        if(lefedepth == rightdepth) return (2<<lefedepth) - 1;
        int leftnum = countNodes(root.left);
        int rightnum = countNodes(root.right);
        return leftnum + rightnum + 1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值