代码随想录第十六天: 二叉树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;
    }
}
相关推荐
ZPC821013 分钟前
docker 镜像备份
人工智能·算法·fpga开发·机器人
ZPC821013 分钟前
docker 使用GUI ROS2
人工智能·算法·fpga开发·机器人
琢磨先生David16 分钟前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
颜酱24 分钟前
栈的经典应用:从基础到进阶,解决LeetCode高频栈类问题
javascript·后端·算法
多恩Stone32 分钟前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
生信大杂烩39 分钟前
癌症中的“细胞邻域“:解码肿瘤微环境的空间密码 ——Nature Cancer 综述解读
人工智能·算法
蜡笔小马1 小时前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
m0_531237171 小时前
C语言-数组练习进阶
c语言·开发语言·算法
qq_454245031 小时前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝1 小时前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode