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

104. 二叉树的最大深度

文章链接:代码随想录 (programmercarl.com)

视频链接:二叉树的高度和深度有啥区别?究竟用什么遍历顺序?很多录友搞不懂 | LeetCode:104.二叉树的最大深度_哔哩哔哩_bilibili

 笔记

  • 非递归方法可以用层序遍历
  • 深度:到根节点的距离(前序遍历);高度:到叶子节点的距离(后序遍历)

C++代码

class Solution {
public:
    int getDepth(TreeNode* root){
        if(root==nullptr)return 0;
        int depl=1+getDepth(root->left);
        int depr=1+getDepth(root->right);
        return depl > depr ? depl : depr;
    }
    int maxDepth(TreeNode* root) {
        int dep=getDepth(root);
        return dep;
    }
};

559. N 叉树的最大深度

文章链接:代码随想录 (programmercarl.com)

笔记 

  • 同上,能解出来,但总感觉哪里怪怪的

C++代码 

class Solution {
public:
    int res=0;
    void pre(Node* root,int depth){
        res=res>depth?res:depth;
        for(Node* child: root->children){
            depth++;
            pre(child,depth);
            depth--;
        }
    }
    int maxDepth(Node* root) {
        if(root){
            pre(root,1);
        }
        return res;
    }
};

111. 二叉树的最小深度

文章链接:代码随想录 (programmercarl.com)

视频链接:看起来好像做过,一写就错! | LeetCode:111.二叉树的最小深度_哔哩哔哩_bilibili

笔记

  • 本题求的是最小深度,只有当左右孩子均是空的时候才能返回正确的最小深度,按照上题的写法,会误判没有左子树或右子树的根节点的深度为1.

C++代码

class Solution {
public:
    int getDepth(TreeNode* root){
        if(root==nullptr)return 0;
        int depl=getDepth(root->left)+1;
        int depr=getDepth(root->right)+1;
        if(root->left==nullptr && root->right!=nullptr){
            return depr;
        }
        if(root->left!=nullptr && root->right==nullptr){
            return depl;
        }
        int res=min(depl,depr);
        return res;
    }
    int minDepth(TreeNode* root) {
        int depth=getDepth(root);
        return depth;


    }
};

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

文章链接:代码随想录 (programmercarl.com)

视频链接:要理解普通二叉树和完全二叉树的区别! | LeetCode:222.完全二叉树节点的数量_哔哩哔哩_bilibili

 C++代码

class Solution {
public:
    int coNo(TreeNode* node){
        if(node==nullptr)return 0;
        
        return 1+coNo(node->left)+coNo(node->right);
    }
    int countNodes(TreeNode* root) {
        int cnt=coNo(root);
        return cnt;

    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值