代码随想录算法训练营第16天

今日刷题4道:104.二叉树的最大深度, 559.n叉树的最大深度,111.二叉树的最小深度,222.完全二叉树的节点个数

●  104.二叉树的最大深度

题目链接/文章讲解/视频讲解: https://programmercarl.com/0104.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6.html

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

559.n叉树的最大深度:树结点有几个孩子是可以得到的

class Solution {
public:
    int maxDepth(Node* root) {
        if(root == NULL) return 0;
        int depth=0;
        for(int i=0;i<root -> children.size();i++){
            depth = max(depth,maxDepth(root->children[i]));
        }
        return depth+1;
    }
};

●  111.二叉树的最小深度

题目链接/文章讲解/视频讲解:https://programmercarl.com/0111.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%B0%8F%E6%B7%B1%E5%BA%A6.html

 

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

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

题目链接/文章讲解/视频讲解:https://programmercarl.com/0222.%E5%AE%8C%E5%85%A8%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E8%8A%82%E7%82%B9%E4%B8%AA%E6%95%B0.html

 普通二叉树解法:

class Solution {
public:
    int countNodes(TreeNode* root) {
        if(root ==NULL) return 0;
        int ll=countNodes(root->left);
        int rr=countNodes(root->right);
        return ll+rr+1;
    }
};
完全二叉树解法:
class Solution {
public:
    int countNodes(TreeNode* root) {
        if (root == nullptr) return 0;
        TreeNode* left = root->left;
        TreeNode* right = root->right;
        int leftDepth = 0, rightDepth = 0; // 这里初始为0是有目的的,为了下面求指数方便
        while (left) {  // 求左子树深度
            left = left->left;
            leftDepth++;
        }
        while (right) { // 求右子树深度
            right = right->right;
            rightDepth++;
        }
        if (leftDepth == rightDepth) {
            return (2 << leftDepth) - 1; // 注意(2<<1) 相当于2^2,所以leftDepth初始为0
        }
        return countNodes(root->left) + countNodes(root->right) + 1;
    }
};
posted @ 2023-01-13 13:39  要坚持刷题啊  阅读(28)  评论(0)    收藏  举报