算法60天:day21

二叉树-二叉搜索树的最小绝对差

力扣链接

class Solution {
public:
    //在二叉搜索树中使用双指针

    int res = INT_MAX;
    TreeNode* pre = nullptr;
    void traversal(TreeNode* cur){
        //采用中序遍历
        //确定终止条件
        if(cur == nullptr) return;
        traversal(cur->left);
        if(pre != nullptr){
            res = min(res,cur->val - pre->val);
        }
        pre = cur;
        traversal(cur->right);
    }
    int getMinimumDifference(TreeNode* root) {
        traversal(root);
        return res;
    }
};

二叉树-二叉搜索树中的众数

力扣链接

 //sort中的比较函数compare要声明为静态成员函数或全局函数,不能作为普通成员函数,否则会报错。
class Solution {
private:
    void searchBST(TreeNode* cur,unordered_map<int,int>& map){
        if(cur == nullptr) return;
        map[cur->val]++;
        searchBST(cur->left,map);
        searchBST(cur->right,map);
        return;
    }
    bool static cmp(const pair<int,int>& a,const pair<int,int>& b){
        return a.second > b.second;
    }
public:
    vector<int> findMode(TreeNode* root) {
        unordered_map<int,int> map; // key:元素,value:出现频率
        vector<int> result;
        if(root == nullptr) return result;
        searchBST(root,map);
        vector<pair<int,int>> vec(map.begin(),map.end());
        sort(vec.begin(),vec.end(),cmp);
        result.push_back(vec[0].first);
        for(int i = 1; i < vec.size(); i++){
            if(vec[i].second == vec[0].second) result.push_back(vec[i].first);
            else break;
        }
        return result;
    }
};

二叉树-二叉树的最近公共祖先

力扣链接

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        //确定终止条件
        if(root == NULL || root == p || root == q) return root;
        TreeNode* left = lowestCommonAncestor(root->left,p,q);
        TreeNode* right = lowestCommonAncestor(root->right,p,q);
        if(left != NULL && right != NULL){
            return root;
        }else if(left != NULL && right == NULL){
            return left;
        }else if(left == NULL && right != NULL){
            return right;
        }else return NULL;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值