代码随想录第十六天: 二叉树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;
    }
}
相关推荐
CoderCodingNo1 分钟前
【GESP】C++五级练习题 luogu-P3353 在你窗外闪耀的星星
开发语言·c++·算法
Anastasiozzzz4 分钟前
LeetCode Hot100 215. 数组中的第K个最大元素
数据结构·算法·leetcode
让我上个超影吧6 分钟前
【力扣76】最小覆盖子串
算法·leetcode·职场和发展
近津薪荼20 分钟前
优选算法——双指针5(单调性)
c++·学习·算法
2401_8576835427 分钟前
C++代码静态检测
开发语言·c++·算法
时艰.32 分钟前
JVM 垃圾收集器(G1&ZGC)
java·jvm·算法
2401_8384725132 分钟前
内存泄漏自动检测系统
开发语言·c++·算法
m0_706653231 小时前
基于C++的爬虫框架
开发语言·c++·算法
diediedei1 小时前
嵌入式数据库C++集成
开发语言·c++·算法
君义_noip1 小时前
洛谷 P3388 【模板】割点(割顶)
c++·算法·图论·信息学奥赛·csp-s