代码随想录第十六天: 二叉树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;
    }
}
相关推荐
汤姆爱耗儿药2 分钟前
数据结构——散列表
数据结构·散列表
UnderTheTime4 分钟前
2025 XYD Summer Camp 7.10 筛法
算法
zstar-_4 分钟前
Claude code在Windows上的配置流程
笔记·算法·leetcode
圆头猫爹19 分钟前
第34次CCF-CSP认证第4题,货物调度
c++·算法·动态规划
秋说22 分钟前
【PTA数据结构 | C语言版】出栈序列的合法性
c语言·数据结构·算法
用户403159863966336 分钟前
多窗口事件分发系统
java·算法
用户403159863966339 分钟前
ARP 缓存与报文转发模拟
java·算法
hi0_61 小时前
03 数组 VS 链表
java·数据结构·c++·笔记·算法·链表
aPurpleBerry1 小时前
hot100 hot75 栈、队列题目思路
javascript·算法
ChoSeitaku1 小时前
NO.3数据结构栈和队列|顺序栈|共享栈|链栈|顺序队|循环队列|链队|双端队列|括号匹配|中缀表达式转后缀|后缀表达式求值
数据结构·microsoft