一、题目
二、思路
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;
}
};