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

题目链接:104. 二叉树的最大深度

后续遍历:整合左右子树的信息,加上自己本身的信息然后返回

在遍历过程中返回左右子树中深度更大的深度值。

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == nullptr) return 0;

        int left, right;
        left = maxDepth(root->left);
        right = maxDepth(root->right);
        if (left > right) return left + 1;
        return right + 1;
    }
};

题目链接:111. 二叉树的最小深度

注意点:本题与上题思路不同,最小深度为根节点到叶子节点之间的距离,下图这种情况深度为2,并不是1,如果继续按照上题中的思路,在根节点1中返回深度小的子树深度,左子树返回值为0,右子树返回值为1,最终结果为1,但是根节点并不是叶子节点,就会出错。

对于仅有一侧有子树的节点需要做特殊处理。

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

题目链接:222. 完全二叉树的节点个数

普通二叉树计算节点个数:

class Solution {
public:
    int countNodes(TreeNode* root) {
        if(!root) return 0;
        
        int left_num = countNodes(root->left);
        int right_num = countNodes(root->right);
        return 1 + left_num + right_num;
    }
};

完全二叉树特性:在递归过程中一定会遍历到一个靠右侧的节点,以这个节点为根节点的二叉树为满二叉树,计算出这个满二叉树的节点个数就可以直接返回不需要再来递归。

class Solution {
public:
    int countNodes(TreeNode* root) {
        if(root == nullptr) return 0;
        TreeNode* left = root->left;
        TreeNode* right = root->right;
        int depth = 1;
        while(left != nullptr && right != nullptr) {
            depth++;
            left = left->left;
            right = right->right;
        }
        if(left == nullptr && right == nullptr) {
            return ((int)1 << depth) - 1;
        }
        else {
            return 1 + countNodes(root->left) + countNodes(root->right);
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值