代码随想录第十六天: 二叉树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;
    }
}
相关推荐
狐573 分钟前
2026-01-18-LeetCode刷题笔记-1895-最大的幻方
笔记·算法·leetcode
Q741_14722 分钟前
C++ 队列 宽度优先搜索 BFS 力扣 662. 二叉树最大宽度 每日一题
c++·算法·leetcode·bfs·宽度优先
Pluchon23 分钟前
硅基计划4.0 算法 动态规划进阶
java·数据结构·算法·动态规划
wzf@robotics_notes1 小时前
振动控制提升 3D 打印机器性能
嵌入式硬件·算法·机器人
机器学习之心1 小时前
MATLAB基于多指标定量测定联合PCA、OPLS-DA、FA及熵权TOPSIS模型的等级预测
人工智能·算法·matlab·opls-da
Loo国昌1 小时前
【LangChain1.0】第八阶段:文档处理工程(LangChain篇)
人工智能·后端·算法·语言模型·架构·langchain
xb11322 小时前
Winforms实战项目:运动控制界面原型
算法
MicroTech20252 小时前
微算法科技(NASDAQ :MLGO)量子安全哈希(QSHA),增强量子时代的区块链安全保障
科技·算法·安全
高洁012 小时前
数字孪生与数字样机的技术基础:建模与仿真
python·算法·机器学习·transformer·知识图谱
不忘不弃2 小时前
模拟内存分配器2
算法