首页 > 编程语言 >算法刷题 Day 16 | 104.二叉树的最大深度 111.二叉树的最小深度 222.完全二叉树的节点个数

算法刷题 Day 16 | 104.二叉树的最大深度 111.二叉树的最小深度 222.完全二叉树的节点个数

时间:2023-01-15 11:46:07浏览次数:61  
标签:node right 16 int 二叉树 深度 left

今日内容:

  • 二叉树的最大深度 559.n叉树的最大深度
  • 二叉树的最小深度
  • 完全二叉树的节点个数

迭代法,大家可以直接过,二刷有精力的时候 再去掌握迭代法。

详细布置

104.二叉树的最大深度 (优先掌握递归)

什么是深度,什么是高度,如何求深度,如何求高度,这里有关系到二叉树的遍历方式。

大家 要先看视频讲解,就知道以上我说的内容了,很多录友刷过这道题,但理解的还不够。

题目链接/文章讲解/视频讲解: https://programmercarl.com/0104.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6.html

Tips:之前用层序遍历解过一次了,这次是使用递归完成的。

我的题解:

class Solution {
public:
    int getDepth(TreeNode* node){
        if(node == NULL){
            return 0;
        }
        int left = getDepth(node->left);
        int right = getDepth(node->right);
        int max = left > right ? left : right;
        return max + 1;
    }

    int maxDepth(TreeNode* root) {
        return getDepth(root);
    }
};

111.二叉树的最小深度 (优先掌握递归)

先看视频讲解,和最大深度 看似差不多,其实 差距还挺大,有坑。

题目链接/文章讲解/视频讲解:https://programmercarl.com/0111.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%B0%8F%E6%B7%B1%E5%BA%A6.html

Tips:这里单层递归的逻辑和求最大深度不太一样,需要注意:

如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。

反之,右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。 最后如果左右子树都不为空,返回左右子树深度最小值 + 1 。

我的题解:

class Solution {
public:     
    int getDepth(TreeNode* node){
        if(node == NULL){
            return 0;
        }
        int left = getDepth(node->left);
        int right = getDepth(node->right);
        if(node->left == NULL && node->right != NULL){
            return 1+ right;
        }
        else if(node->left != NULL && node->right == NULL){
            return 1+left;
        }
        else {
            return min(left,right) + 1;
        }

    }
    int minDepth(TreeNode* root) {
        return getDepth(root);
    }
};

222.完全二叉树的节点个数(优先掌握递归)

需要了解,普通二叉树 怎么求,完全二叉树又怎么求

题目链接/文章讲解/视频讲解:https://programmercarl.com/0222.%E5%AE%8C%E5%85%A8%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E8%8A%82%E7%82%B9%E4%B8%AA%E6%95%B0.html

Tips:二叉树的写法有两种,递归或层序遍历,在这道题上能用但是效率比较低。

因为题目说了是完全二叉树,所以可以针对其性质写出相应的代码。

我的题解:

class Solution {
public:
    int countNodes(TreeNode* root) {
        if(root == NULL){
            return 0;
        }
        TreeNode* left = root->left;
        TreeNode* right = root->right;
        int leftDepth = 0;
        int rightDepth = 0;
        while(left){
            leftDepth++;
            left = left->left;
        }
        while(right){
            rightDepth++;
            right = right->right;
        }
        if(leftDepth == rightDepth){
            return (2 << leftDepth) - 1;
        }
        return countNodes(root->left) + countNodes(root->right) + 1;
    }
};

标签:node,right,16,int,二叉树,深度,left
From: https://www.cnblogs.com/GavinGYM/p/17053262.html

相关文章