代码随想录训练营第十六天 | 104.二叉树的最大深度、111.二叉树的最小深度、222.完全二叉树的节点个数

104.二叉树的最大深度

题目链接:. - 力扣(LeetCode)

文档讲解:代码随想录

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

状态:通过

解题思路:可以使用后续遍历的方法,先求出子树的最大高度,再求出整颗树的高度,就得到了二叉树的最大深度。 

代码实现:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == NULL) return 0;
        int depth1 = maxDepth(root->left);
        int depth2 = maxDepth(root->right);
        int depth = 1 + max(depth1, depth2);
        return depth;
    }
};

111.二叉树的最小深度

题目链接:. - 力扣(LeetCode)

文档讲解:代码随想录

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

状态:未通过

 代码实现:

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;
        }
        if(root -> left != NULL && root->right == NULL){
            return 1 + leftDepth;
        }
        return 1 + min(leftDepth, rightDepth);
    }
};

题目难点:容易忽略左孩子或者右孩子为空的情况。

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

题目链接:. - 力扣(LeetCode)

文档讲解:代码随想录

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

状态:通过

初步解题思路:使用后序遍历的方法,遍历整个二叉树,进而统计二叉树的节点个数 。

代码实现:

class Solution {
public:
    int countNodes(TreeNode* root) {
        if(root == NULL) return 0;
        int leftNum = countNodes(root->left);
        int rightNum = countNodes(root->right);
        int result = leftNum + rightNum + 1;
        return result;
    }
};

看完代码随想录后解题思路:利用完全二叉树的特性来求二叉树的节点数,这样可以不用遍历所有的二叉树节点。

代码实现:

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){
            left = left->left;
            leftDepth++;
        }
        while(right){
            right = right->right;
            rightDepth++;
        }
        if(leftDepth == rightDepth){
            return (2 << leftDepth) - 1;
        }
        return countNodes(root->left) + countNodes(root->right) + 1;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值