Code Caprice Algorithm Training Camp Día 16 | 104. La profundidad máxima de un árbol binario | 111. La profundidad mínima de un árbol binario | 222. El número de nodos en un árbol binario completo

/**
 * 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 {
    
    
    int maxnum=0;
    void travesal(TreeNode* root,int depth){
    
    
        
        if(root==nullptr){
    
    
            return;}
        depth++;    
        maxnum=max(maxnum,depth);
        travesal(root->left,depth);
        travesal(root->right,depth);
    }
public:
    int maxDepth(TreeNode* root) {
    
    
        travesal(root,0);
        return maxnum;
    }
};

111. Profundidad mínima del árbol binario

/**
 * 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 {
    
    
    int mm=INT_MAX;
    void dfs(TreeNode* root,int depth){
    
    
        if(root==nullptr)return;
        depth++;
        if(root->left==nullptr&&root->right==nullptr){
    
    
            mm=min(mm,depth);
        }
        dfs(root->left,depth);
        dfs(root->right,depth);
    }
public:
    int minDepth(TreeNode* root) {
    
    
        if(root==nullptr)return 0;
        dfs(root,0);
        return mm; 
    }
};

222. El número de nodos en un árbol binario completo

/**
 * 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) {
    
    
        if(root==nullptr)return 0;
        TreeNode* left=root->left;
        TreeNode* right=root->right;
        int ldepth=0,rdepth=0;
        while(left){
    
    
            left=left->left;
            ldepth++;
        }
        while(right!=nullptr){
    
    
            right=right->right;
            rdepth++;
        }
        if(ldepth==rdepth){
    
    
            return (2<<ldepth)-1;
        }
        
        return countNodes(root->left)+countNodes(root->right)+1;
    
    }
};

Guess you like

Origin blog.csdn.net/weixin_43541510/article/details/132202608