Code Caprice Training Camp 21 Days | 530. The Minimum Absolute Difference of a Binary Search Tree | 501. The Mode in a Binary Search Tree | 236. The Nearest Common Ancestor of a Binary Tree

/**
 * 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 {
    
    
    
    void dfs(TreeNode*root,vector<int>&vec){
    
    
        if(root==nullptr)return ;
        dfs(root->left,vec);
        vec.push_back(root->val);
        dfs(root->right,vec);

    }
public:
    int getMinimumDifference(TreeNode* root) {
    
    
        vector<int>vec;
        dfs(root,vec);
        int res=INT_MAX;
        for(int i=0;i<vec.size()-1;i++){
    
    
            res=min(abs(vec[i+1]-vec[i]),res);

        }
        return res;
    }
};
/**
 * 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 {
    
    
    vector<int>res;
    int count ;
    int maxcou;
    TreeNode*pre=nullptr;
    void back(TreeNode*root){
    
    
        if(root==nullptr)return ;
        back(root->left);
        if(pre==nullptr){
    
    
            count=1;
        }else if(pre->val==root->val){
    
    
            count++;
        }else{
    
    
            count=1;
        }
        if(count==maxcou){
    
    
            res.push_back(root->val);
        }
        if(count>maxcou){
    
    
            maxcou=count;
            res.clear();
            res.push_back(root->val);
        }
        pre=root;
        back(root->right);
    }
public:
    vector<int> findMode(TreeNode* root) {
    
    
        back(root);
        return res;
    }
};
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    
    
        if (root == q || root == p || root == NULL) return root;
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        if (left != NULL && right != NULL) return root;

        if (left == NULL && right != NULL) return right;
        else if (left != NULL && right == NULL) return left;
        else  {
    
     //  (left == NULL && right == NULL)
            return NULL;
        }

    }
};

Guess you like

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