代码随想录第十六天: 二叉树part03

力扣222 完全二叉树的节点个数

java 复制代码
class Solution {
    public int countNodes(TreeNode root) {
        if(root == null) return 0;
        TreeNode leftnode = root.left;
        int leftdepth = 0;
        TreeNode rightnode = root.right;
        int rightdepth = 0;
        while(leftnode != null) {
            leftnode = leftnode.left;
            leftdepth++;
        }
        while(rightnode != null) {
            rightnode = rightnode.right;
            rightdepth++;
        }
        if(rightdepth == leftdepth) return (2 << rightdepth) - 1;
        else {
            int leftnum = countNodes(root.left);
            int rightnum = countNodes(root.right);
            return 1 + leftnum + rightnum;
        }
    }
}

力扣111 二叉树的最小深度

java 复制代码
class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        int leftdepth = minDepth(root.left);
        int rightdepth = minDepth(root.right);
        if(root.left == null && root.right != null) return 1 + rightdepth;
        else if(root.left != null && root.right == null) return 1 + leftdepth;
        else if(root.left == null && root.right == null) return 1;
        else return 1 + Math.min(leftdepth, rightdepth);
    }
}

力扣104 二叉树的最大深度

java 复制代码
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        int leftheight = maxDepth(root.left);
        int rightheight = maxDepth(root.right);
        int height = 1 + Math.max(leftheight, rightheight);
        return height;
    }
}
相关推荐
mftang4 小时前
BSS段、Data段、Text段的具体含义和数据特性
数据库·算法
王老师青少年编程4 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【反悔贪心】:建筑抢修
c++·算法·贪心·反悔贪心·csp·信奥赛·建筑抢修
地球资源数据云4 小时前
1960年-2024年中国棉花产量数据集
大数据·数据结构·数据仓库·人工智能
TianFuRuanJian4 小时前
科普 | 仿真中的“体力活”:网格验证能不能自动化?
算法·仿真·ai网格
leoufung4 小时前
LeetCode 135. Candy:从直觉到最优解的完整推导
算法·leetcode·职场和发展
WHS-_-20224 小时前
Tensor-Based Target Sensing for Resource-Irregular ISAC Systems
linux·人工智能·算法
成都易yisdong5 小时前
高程异常计算器:一款集成Geoid、重力场与地磁场的专业工具
算法
王老师青少年编程5 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【反悔贪心】:种树
c++·算法·贪心·反悔贪心·csp·信奥赛·种树
南宫萧幕5 小时前
基于 PSO 的 HEV 能量管理策略:从联合仿真建模到排错实战
开发语言·python·算法·matlab·控制
生物信息与育种5 小时前
全基因组重测序及群体遗传与进化分析技术服务指南
人工智能·深度学习·算法·数据分析·r语言