501. 二叉搜索树中的众数

发布时间 2023-04-11 15:57:00作者: xiazichengxi

给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。

如果树中有不止一个众数,可以按 任意顺序 返回。

假定 BST 满足如下定义:

结点左子树中所含节点的值 小于等于 当前节点的值
结点右子树中所含节点的值 大于等于 当前节点的值
左子树和右子树都是二叉搜索树

class Solution {
public:
    void inorder(TreeNode* root){
        if(root == nullptr) return;
        mp[root->val]++;
        inorder(root->left);
        inorder(root->right);
    }
    vector<int> findMode(TreeNode* root) {
        inorder(root);
        vector<std::pair<int, int>> vec;
        for (const auto& item : mp)
        {
            vec.emplace_back(item);
        }
        std::sort(vec.begin(),vec.end(),
        [](const auto &a,const auto &b)->bool{  return a.second>b.second;});
        vector<int> res;
        int k = vec[0].second;
        for(const auto &x:vec){
            if(x.second == k) res.emplace_back(x.first);
        }
        return res;
    }
    void inorder_t(TreeNode* root){
        if(root == nullptr) return;
        inorder_t(root->left);
        if(pre == nullptr){
            count =  1;
        }
        else if(pre->val == root->val){
            count++;
        }
        else{
            count = 1;
        }
        pre = root;
        if(count == max){
            res.emplace_back(root->val);
        }
        if(count > max){
            res.clear();
            res.emplace_back(root->val);
            max = count;
        }
        inorder_t(root->right);
    }
    vector<int> findMode(TreeNode* root){
        count = 0;
        max = 0;
        this->pre = nullptr;
        res.clear();
        inorder_t(root);
        return res;
    }
private:
    std::unordered_map<int,int> mp;
    int count;
    int max;
    TreeNode* pre;
    vector<int> res;
};