代码随想录第十六天: 二叉树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;
    }
}
相关推荐
手写码匠1 分钟前
手写 AI 智能路由系统:从零构建多模型调度与负载均衡
人工智能·深度学习·算法·aigc
sheeta19981 分钟前
LeetCode 每日一题笔记 日期:2026.05.14 题目:2784. 检查数组是否是好的
笔记·算法·leetcode
故事还在继续吗3 分钟前
DPDK 教程(三):多队列 + RSS + 多 worker 的最小转发 / Echo
算法·哈希算法·dpdk
AI科技星4 分钟前
全域数学·体积与表面积通项定理【乖乖数学】
人工智能·算法·数学建模·数据挖掘·机器人
孬甭_5 分钟前
顺序表详解
c语言·数据结构
Yingjun Mo10 分钟前
1. 在线学习引言
学习·算法
李日灐13 分钟前
< 12 > Linux进程:进程虚拟地址空间机制 —— 内存管理的美学
linux·运维·算法
Mr_pyx22 分钟前
LeetCode 226. 翻转二叉树(多种解法详解)
算法·深度优先
qeen8722 分钟前
【算法笔记】各种常见排序算法详细解析(上)
c语言·数据结构·c++·学习·算法·排序算法
绿蕉23 分钟前
自动驾驶技术的演进之路:从规则算法到端到端架构
算法·架构·自动驾驶