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