代码随想录第十六天: 二叉树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;
    }
}
相关推荐
小欣加油11 分钟前
leetcode 3 无重复字符的最长子串
c++·算法·leetcode
月盈缺3 小时前
学习嵌入式的第二十二天——数据结构——双向链表
数据结构·学习·链表
猿究院--王升3 小时前
jvm三色标记
java·jvm·算法
一车小面包3 小时前
逻辑回归 从0到1
算法·机器学习·逻辑回归
科大饭桶4 小时前
C++入门自学Day14-- Stack和Queue的自实现(适配器)
c语言·开发语言·数据结构·c++·容器
tt5555555555555 小时前
字符串与算法题详解:最长回文子串、IP 地址转换、字符串排序、蛇形矩阵与字符串加密
c++·算法·矩阵
元亓亓亓5 小时前
LeetCode热题100--101. 对称二叉树--简单
算法·leetcode·职场和发展
躲在云朵里`5 小时前
深入理解数据结构:从数组、链表到B树家族
数据结构·b树
不会学习?6 小时前
算法03 归并分治
算法
NuyoahC6 小时前
笔试——Day43
c++·算法·笔试