代码随想录第十六天: 二叉树part03

力扣222 完全二叉树的节点个数

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 二叉树的最小深度

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 二叉树的最大深度

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;
    }
}

最近更新

  1. TCP协议是安全的吗?

    2024-04-06 05:18:07       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-06 05:18:07       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-06 05:18:07       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-06 05:18:07       20 阅读

热门阅读

  1. LeetCode //C - 154. Find Minimum in Rotated Sorted Array II

    2024-04-06 05:18:07       15 阅读
  2. 【电路笔记】-逻辑或门

    2024-04-06 05:18:07       15 阅读
  3. 掌握ChatGPT技巧,写出拔尖学术论文

    2024-04-06 05:18:07       14 阅读
  4. 【算法集训】基础算法:前缀和 | 习题篇

    2024-04-06 05:18:07       14 阅读
  5. 【小说拉期待感的几个小技巧】

    2024-04-06 05:18:07       18 阅读
  6. PyTorch搭建Informer实现长序列时间序列预测

    2024-04-06 05:18:07       16 阅读
  7. Mysql不同条件设置相同的值(使用子查询)

    2024-04-06 05:18:07       17 阅读
  8. AI大模型学习

    2024-04-06 05:18:07       11 阅读
  9. 文字识别 Optical Character Recognition,OCR CTC STN

    2024-04-06 05:18:07       23 阅读
  10. Docker in Docker原理与实战

    2024-04-06 05:18:07       15 阅读