力扣打卡第23天 二叉搜索树中的众数

发布于:2025-07-11 ⋅ 阅读:(15) ⋅ 点赞:(0)

501. 二叉搜索树中的众数

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

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

假定 BST 满足如下定义:

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

示例 1:

输入:root = [1,null,2,2]
输出:[2]

示例 2:

输入:root = [0]
输出:[0]

提示:

  • 树中节点的数目在范围 [1, 104] 内
  • -105 <= Node.val <= 105

方法一:当做普通的二叉树处理,用map

/**
 * 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:
    void get_mp(TreeNode* root,unordered_map<int,int>& mp){
        if(root==nullptr)return;
        mp[root->val]++;
        if(root->left)get_mp(root->left,mp);
        if(root->right)get_mp(root->right,mp);
    }
    bool static cmp(pair<int,int> a,pair<int,int>b){//这里少了static就会报错
        return a.second>b.second;//seconde不用大括号后面
    }
    vector<int> findMode(TreeNode* root) {
        //肯定要用到map,但是进需要无须map即可,后面排序自己排
        unordered_map<int,int>mp;
        get_mp(root,mp);
        vector<pair<int, int>> vec(mp.begin(), mp.end());//mp不能排序,需要先转移到vec里面
        sort(vec.begin(),vec.end(),cmp);
        vector<int>res;
        res.push_back(vec[0].first);
        for(int i=1;i<vec.size();i++){
            if(vec[i].second==vec[0].second)res.push_back(vec[i].first);
        }
        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 {
private:
    vector<int>res;
    TreeNode* pre;
    int max_count;
    int count;
    void get(TreeNode* root){
        if(root==nullptr)return ;
        if(root->left)get(root->left);//左
        //中
        if(pre==nullptr){
            count=1;
            pre=root;
        }
        else if(pre->val==root->val){
            count++;
            pre=root;
        }
        else{
            count=1;
            pre=root;
        }
        if(count>max_count){
            max_count=count;
            res.clear();
            res.push_back(root->val);
        }
        else if(count==max_count){
            res.push_back(root->val);
        }

        if(root->right)get(root->right);//右

    }
public:
    vector<int> findMode(TreeNode* root) {
        //利用二叉搜索树的性质(中序遍历有大小关系)
        max_count=0;
        pre=nullptr;
        count=0;
        res.clear();
        get(root);
        return res;
    }
};


网站公告

今日签到

点亮在社区的每一天
去签到