10.25 log

文章介绍了两种在二叉搜索树中查找众数的方法,一种使用unordered_map记录节点频率并排序,另一种利用中序遍历和计数器实现,后者效率更高。Solution类提供了findMode函数实现这两种策略。
摘要由CSDN通过智能技术生成

501. 二叉搜索树中的众数 

class Solution {
private:
    unordered_map<int,int> ans;
    TreeNode* pre=NULL;
    void traversal(TreeNode* root){
        if(!root) return;
        ans[root->val]++;
        traversal(root->left);
        traversal(root->right);
    }
    bool static cmp (const pair<int, int>& a, const pair<int, int>& b) {
    return a.second > b.second;
}
public:
    vector<int> findMode(TreeNode* root) {
        vector<int> result;
        if(!root) return result;
        traversal(root);
        vector<pair<int,int>> vec(ans.begin(),ans.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;
    }
};

先遍历一遍二叉树,用unorderd_map来记录键值对,键为二叉树的值,值为出现的频率,前中后序遍历皆可,然后用一个pair类型的vector数组储存键值对,并对值进行排序,然后找出值相同的键值对,储存键

class Solution {
private:
    TreeNode* pre=NULL;
    vector<int> result;
    int maxCount=0;
    int count=1;
    void traversal(TreeNode* root){
            if(!root) return;
            traversal(root->left);
            if(pre){
                if(pre->val==root->val){
                    count++;
                }else count=1;
            }
            pre=root;
            if(count==maxCount){
                result.push_back(root->val);
            }else if(count>maxCount){
                result.clear();
                result.push_back(root->val);
                maxCount=count;
            }
            traversal(root->right);
        }
public:
    vector<int> findMode(TreeNode* root) {
        if(!root) return result;
        traversal(root);
        return result;
    }
};

这版代码比上版代码运行起来效率更高,利用一次二叉搜索树的中序遍历就能搜索出二叉树的众数,这个方法巧在运用了两个count,一个count,一个maxCount,当前后指针相等时,count增加,不等count打回原形,等于1,maxCount根据count而后赋值,count等于maxCount时,result数组添加,count大于macxCount数组时,清空数组,再添加,同时maxCount等于此时的count

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值