代码随想录第十六天: 二叉树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;
    }
}
相关推荐
We་ct4 分钟前
LeetCode 212. 单词搜索 II:Trie+DFS 高效解法
开发语言·算法·leetcode·typescript·深度优先·图搜索算法·图搜索
样例过了就是过了7 分钟前
LeetCode热题100 路径总和 III
数据结构·c++·算法·leetcode·链表
lxh01138 分钟前
函数防抖题解
前端·javascript·算法
再难也得平12 分钟前
力扣41. 缺失的第一个正数(Java解法)
数据结构·算法·leetcode
颜酱13 分钟前
环检测与拓扑排序:BFS/DFS双实现
javascript·后端·算法
IronMurphy19 分钟前
【算法二十】 114. 寻找两个正序数组的中位数 153. 寻找旋转排序数组中的最小值
java·算法·leetcode
实心儿儿21 分钟前
算法2:链表的中间结点
数据结构·算法·链表
代码探秘者22 分钟前
【Java集合】ArrayList :底层原理、数组互转与扩容计算
java·开发语言·jvm·数据库·后端·python·算法
颜酱23 分钟前
理解并查集Union-Find:从原理到练习
javascript·后端·算法
玛卡巴卡ldf25 分钟前
【LeetCode 手撕算法】(双指针) 1-两数之和、283-移动零、11-盛最多水的容器、15-三数之和
数据结构·算法·leetcode