代码随想录第十六天: 二叉树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;
    }
}
相关推荐
_F_y25 分钟前
二叉树中的深搜
算法
锅包一切39 分钟前
PART17 一维动态规划
c++·学习·算法·leetcode·动态规划·力扣·刷题
Polaris北44 分钟前
第二十六天打卡
c++·算法·动态规划
Stringzhua2 小时前
队列-优先队列【Queue3】
java·数据结构·队列
罗湖老棍子2 小时前
【例 2】选课(信息学奥赛一本通- P1576)
算法·树上背包·树型动态规划
每天要多喝水2 小时前
动态规划Day33:编辑距离
算法·动态规划
每天要多喝水2 小时前
动态规划Day34:回文
算法·动态规划
weixin_477271692 小时前
马王堆帛书《周易》系统性解读(《函谷门》原创)
算法·图搜索算法
AomanHao3 小时前
【ISP】基于暗通道先验改进的红外图像透雾
图像处理·人工智能·算法·计算机视觉·图像增强·红外图像
We་ct3 小时前
LeetCode 226. 翻转二叉树:两种解法(递归+迭代)详解
前端·算法·leetcode·链表·typescript