2021-11-09每日刷题打卡

一、Leetcode-104:二叉树的最大深度

1.1 问题描述

2021-11-09每日刷题打卡

1.2 问题分析

2021-11-09每日刷题打卡

1.3 问题解决

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:  
    int maxDepth(TreeNode* root) {
        if(root == nullptr) return 0;

        return max(maxDepth(root->left), maxDepth(root->right)) + 1;
    }
};

二、Leetcode-111:二叉树的最小深度

2.1 问题描述

2021-11-09每日刷题打卡

2.2 问题分析

2021-11-09每日刷题打卡

2.3 问题解决

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root == nullptr) return 0;

        int m1 = minDepth(root->left);
        int m2 = minDepth(root->right);
        
        return root->left == nullptr || root->right == nullptr
               ? m1 + m2 + 1 : min(m1, m2) + 1;
    }
};

三、Leetcode-222:完全二叉树的节点个数

3.1 问题描述

2021-11-09每日刷题打卡

3.2 问题分析

2021-11-09每日刷题打卡

3.3 问题解决

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int countNodes(TreeNode* root) {
        vector<vector<int>> level;
        queue<TreeNode*> q;

        if(root != nullptr) q.push(root);
        else return 0;

        while(!q.empty())
        {
            int n = q.size();
            vector<int> v;

            for(int i = 0; i < n; i++)
            {
                TreeNode* node = q.front();
                q.pop();
                v.push_back(node->val);

                if(node->left != nullptr) q.push(node->left);
                if(node->right != nullptr) q.push(node->right);
            }
            level.push_back(v);
        }

        return pow(2, level.size()-1) - 1 + level[level.size()-1].size();
    }
};
上一篇:链表中环的入口结点


下一篇:[C/C++ 基础](类型转换系列三) dynamic_cast与std::dynamic_pointer_castcast