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

LeetCode104 二叉树的最大深度

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

文章链接:二叉树的最大深度

思路

使用层序遍历是最为合适的,因为最大的深度就是二叉树的层数。

代码

class Solution {
public:
    int maxDepth(TreeNode* root) {
        queue<TreeNode*> que;
        int depth = 0;
        if(root != nullptr)
            que.push(root);
        while(!que.empty())
        {
            int size = que.size();
            while(size--)
            {
                TreeNode* node = que.front();
                que.pop();
                if(node->left)
                    que.push(node->left);
                if(node->right)
                    que.push(node->right);
            }
            depth++;
        }
        return depth;
    }
};

LeetCode111 二叉树的最小深度

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

文章链接:二叉树的最小深度

思路

本题也可以用层序遍历,不过要注意的是,只有当节点的左右孩子都为空时,才说明是遍历的最低点了。

代码

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (root == NULL) return 0;
        int depth = 0;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty()) {
            int size = que.size();
            depth++; // 记录最小深度
            for (int i = 0; i < size; i++) {
                TreeNode* node = que.front();
                que.pop();
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
                if (!node->left && !node->right) { // 当左右孩子都为空的时候,说明是最低点的一层了,退出
                    return depth;
                }
            }
        }
        return depth;
    }
};

LeetCode222 完全二叉树的节点个数

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

文章链接:完全二叉树的节点个数

视频链接:完全二叉树的节点个数

思路

因为是完全二叉树,所以想着直接层序遍历累加节点个数。

还真的AC了,层序遍历算是一种暴力解法吧。

代码

class Solution {
public:
    int countNodes(TreeNode* root) {
        queue<TreeNode*> que;
        if(root !=nullptr)
            que.push(root);
        int count = 0;
        while(!que.empty())
        {
            int size = que.size();
            for(int i = 0;i < size;i++)
            {
                TreeNode* node = que.front();
                que.pop();
                count++;
                if(node->left)
                    que.push(node->left);
                if(node->right)
                    que.push(node->right);
            }
        }
        return count;
    }
};

你可能感兴趣的:(代码随想录,算法,数据结构)