leetcode501-二叉搜索树中的众数

leetcode501-二叉搜索树中的众数

一、题目

在这里插入图片描述

二、思路

1、使用字典的数据结构,因为字典中可以存储key和value,也就代表着节点值和节点值的出现次数。
2、map默认为对key进行升序排列,但是本题目中的排列考虑因素是value(出现次数),也不能够使用sort(),因为sort是对线性的容器排序,map是集合,所以此路不同。
(1)使用vector<pair<int,int>>解决2问题,在vector中存储键值对,然后写一个cmp函数调整sort的默认策略。
(2)cmp代码

    static bool cmp(const pair<int, int>& x, const pair<int, int>& y)  
    {  
	    return x.second > y.second;  
    } 

(3)注意cmp函数这里有一个小坑,要把cmp函数设置为静态函数,不然在leetcode默认的调用中无法调用。
在这里插入图片描述
在这里插入图片描述

三、整体代码

/**
 * 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:
    vector<pair<int,int>>tVector;//存储键值对
    vector<int>res;//存储结果
    map<int,int>m;//存储数字和出现次数
    static bool cmp(const pair<int, int>& x, const pair<int, int>& y)  
    {  
	    return x.second > y.second;  
    } 

    void dfs(TreeNode* root)
    {
        if(root==NULL) return;
        if(root->left) dfs(root->left);
        m[root->val]++;
        if(root->right) dfs(root->right);
    }

    void get_res()
    {
    	//将map中的键值对放入tVector中
        for (map<int, int>::iterator curr = m.begin(); curr != m.end(); curr++)   
		    tVector.push_back(make_pair(curr->first, curr->second));
        sort(tVector.begin(),tVector.end(),cmp); 
        //因为众数可能有很多个,所以使用循环获取所有众数
        int res_num=tVector[0].second;
        for(int i=0;i<tVector.size();i++)
        {
            if(tVector[i].second==res_num)
            {
                res.push_back(tVector[i].first);
            }
        }
    }

    vector<int> findMode(TreeNode* root) {
        dfs(root);
        get_res();
        return res;
    }
};

四、AC情况

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值