代码随想录算法训练营第16天|104.二叉树的最大深度 559.n叉树的最大深度|111.二叉树的最小深度|222.完全二叉树的节点个数

二叉树用到的迭代法,可以直接过,二刷有精力的时候 再去掌握迭代法。

104.二叉树的最大深度  559.n叉树的最大深度

背景:(优先掌握递归)什么是深度,什么是高度,如何求深度,如何求高度,这里有关系到二叉树的遍历方式。要先看视频讲解,就知道以上我说的内容了,很多录友刷过这道题,但理解的还不够。

题目链接/文章讲解/视频讲解: 代码随想录

做题初始状态:不会

学完后想法:思路简单

思路关键点:如何求深度?后序遍历。共三步骤:

  1. 确定递归函数的参数和返回值
  2. 确定终止条件:如果为空节点的话,就返回0,表示高度为0。
  3. 确定单层递归的逻辑:

今日收获+学习时长:代码可以看懂。时长不详。

104

class Solution {
public:
    int getdepth(TreeNode* node) { // 确定函数参数和返回值
        if (node == NULL) return 0; //确定终止条件
        int leftdepth = getdepth(node->left);       // 左
        int rightdepth = getdepth(node->right);     // 右
        int depth = 1 + max(leftdepth, rightdepth); // 中
        return depth;
    }
    int maxDepth(TreeNode* root) {
        return getdepth(root); // 函数调用
    }
};

559

class Solution {
public:
    int maxDepth(Node* root) {
        if (root == 0) return 0;
        int depth = 0;
        for (int i = 0; i < root->children.size(); i++) {
            depth = max (depth, maxDepth(root->children[i]));
        }
        return depth + 1;
    }
};

111.二叉树的最小深度

背景:(优先掌握递归)先看视频讲解,和最大深度 看似差不多,其实 差距还挺大,有坑。

题目链接/文章讲解/视频讲解:代码随想录

做题初始状态:不会

学完后想法:最小深度和最大深度的中间过程差别还很大

思路细节:本题 最小深度 定义是:根节点到叶子结点的最小距离

今日收获+学习时长:大概对最小深度了解了。学习时长,不详。

class Solution {
public:
    int getDepth(TreeNode* node) {
        if (node == NULL) return 0;
        int leftDepth = getDepth(node->left);           // 左
        int rightDepth = getDepth(node->right);         // 右
                                                        // 中
        // 当一个左子树为空,右不为空,这时并不是最低点
        if (node->left == NULL && node->right != NULL) { 
            return 1 + rightDepth;
        }   
        // 当一个右子树为空,左不为空,这时并不是最低点
        if (node->left != NULL && node->right == NULL) { 
            return 1 + leftDepth;
        }
        int result = 1 + min(leftDepth, rightDepth);
        return result;
    }

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

222.完全二叉树的节点个数

背景:(优先掌握递归)需要了解,普通二叉树 怎么求,完全二叉树又怎么求

题目链接/文章讲解/视频讲解:代码随想录

做题初始状态:不会

学习时长:学习时长,不详。

// 版本一
class Solution {
private:
    int getNodesNum(TreeNode* cur) {
        if (cur == NULL) return 0;
        int leftNum = getNodesNum(cur->left);      // 左
        int rightNum = getNodesNum(cur->right);    // 右
        int treeNum = leftNum + rightNum + 1;      // 中
        return treeNum;
    }
public:
    int countNodes(TreeNode* root) {
        return getNodesNum(root);
    }
};

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值