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

104.二叉树的最大深度

初见想法:直接往下遍历,然后深度+1,维护一个最大深度

class Solution {
public:

    int maxDepth(TreeNode* root) {

        return getDepth(root);
    }

    int getDepth(TreeNode* node)
    {
        if (node == nullptr) return 0;

        int leftdepth = getDepth(node->left);
        int rightdepth = getDepth(node->right);

        return max(leftdepth, rightdepth) + 1; 
    }

};
  1. 使用递归的方法,先遍历至最底层,然后深度不断往上+1

111.二叉树的最小深度

初见想法:使用层序遍历,遍历至某一node,其左右子树皆为空, 需要维护一个depth

层序迭代法:

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

        queue<TreeNode*> que;
        que.push(root);

        while (!que.empty())
        {
            Depth++;
            int sz = que.size();

            for (int i = 0; i <sz; i++)
            {
                TreeNode* node = que.front();
                que.pop();

                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);

                if (node->left == nullptr && node->right == nullptr) return Depth;
            }
        }

        return Depth;
    }
};

递归法:

class Solution {
public:
    int minDepth(TreeNode* root) 
    {
        return getdepth(root);
    }

    int getdepth(TreeNode* node)
    {
        if (node == nullptr) return 0;

        int leftdepth = getdepth(node->left);
        int rightdepth = getdepth(node->right);

        if (node->left == nullptr && node->right != nullptr) return 1  + rightdepth;
        if (node->left != nullptr && node->right == nullptr) return 1 + leftdepth;

        return 1 + min(leftdepth, rightdepth);
    }
};

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

初见想法:看到这一题,啪就搞起来,很快啊,一个cnt, 一个递归遍历

class Solution {
public:
    int cnt = 0;
    int countNodes(TreeNode* root) {
        traversal(root);
        return cnt;
    }

    void traversal(TreeNode* node)
    {
        if (node == nullptr) return;

        cnt++;
        traversal(node->left);
        traversal(node->right);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值