代码随想录第十六天: 二叉树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;
    }
}
相关推荐
林shir7 分钟前
Java基础1.7-数组
java·算法
Jeremy爱编码33 分钟前
leetcode课程表
算法·leetcode·职场和发展
甄心爱学习42 分钟前
SVD求解最小二乘(手写推导)
线性代数·算法·svd
努力学算法的蒟蒻1 小时前
day46(12.27)——leetcode面试经典150
算法·leetcode·面试
Blockbuater_drug1 小时前
InChIKey: 分子的“化学身份证”,从哈希原理到全球监管合规(2025)
算法·哈希算法·inchikey·rdkit·分子表达·化学信息学
橙汁味的风2 小时前
2EM算法详解
人工智能·算法·机器学习
维构lbs智能定位2 小时前
北斗卫星导航定位从核心框架到定位流程详解(一)
算法·北斗卫星导航定位系统
byzh_rc2 小时前
[算法设计与分析-从入门到入土] 动态规划
算法·动态规划
Halo_tjn2 小时前
Java List集合知识点
java·开发语言·windows·算法·list
云飞云共享云桌面2 小时前
河北某机器人工厂8个研发设计共享一台SolidWorks云主机
运维·服务器·网络·数据库·算法·性能优化·机器人