代码随想录算法训练营第29天|LeetCode501.二叉搜索树中的众数
1、LeetCode501.二叉搜索树中的众数
第一想法
思路
直接遍历二叉树,然后用一个unordered_map记录每个数出现的频数,最后返回最大的几个。
评价第一想法:其实是普通二叉树求解的方法,最后还需要将map转换成vector并排序。
代码
犯错
- unordered_map 查找find:
auto it = map.find(root->val);
是否找到则判断it!=map.end()
- unordered_map 插入insert:
map.insert({root->val, 1})
unordered_map中的元素以pair方式存在,所以访问的时候也可以使用pair.first访问 - unordered_map 遍历:
for(auto it = map.begin(); it!=map.end(); it++)
- sort可以传入比较函数,
sort(vec.begin(),vec.end(),compare)
比较函数需要是static的 - map转换成vector
vector<pair<int, int>> vec(map.begin(), map.end());
class Solution {
public:
unordered_map<int, int> map;
void traversal(TreeNode* root){
// 中序遍历
if(root == NULL) return;
traversal(root->left);
auto it = map.find(root->val); //注意这里查找的方法
if(it!=map.end()){
map[root->val]++;
}
else{
map.insert({root->val, 1});
}
traversal(root->right);
}
// 比较函数 注意需要声明是static的
static bool compare(pair<int, int> a, pair<int, int> b){
return a.second > b.second;
}
vector<int> findMode(TreeNode* root) {
vector<pair<int, int> > vec;
vector<int> res;
if(root == NULL) return res;
traversal(root);
// 转换成vector数组 ?如何遍历map呀
// 有更简单的转换方式
for(auto it = map.begin(); it!=map.end(); it++){
vec.push_back(*it);
}
//排序
sort(vec.begin(),vec.end(),compare);
int cnt=0;
for(int i=0; i<vec.size() ;i++){
if(vec[i].second == vec[0].second){
res.push_back(vec[i].first);
}
}
return res;
}
};
双指针思路
双指针:pre和cur
maxCount:统计所有元素的最高频率
count:单个元素的频率。当cur没有pre指针时,count归1;当cur和pre不相等时,count归1。
若count==maxCount,则放入结果集。(why?如何保证是最大频率)
递归三部曲
- 参数和返回值
- 终止条件:cur为空,直接返回
- 单层逻辑:
若pre为空,count=1;若precur,count++;否则,即pre->val!=cur->val,count=1。
若countmaxCount,加入res;
若count>maxCount,更新maxCount,清空res,新的再加入res。
更新pre=cur。(双指针更新的灵魂)
代码
vector一键清空:vec.clear()
class Solution {
public:
// 法2
int count;
int maxCount;
vector<int> res;
TreeNode* pre = NULL;//初始化为空
void traversal2(TreeNode* cur){
// 终止条件
if(cur == NULL ) return;
// 左
traversal2(cur->left);
// 单层逻辑,中
if(pre == NULL)
count=1;
else if(pre->val == cur->val)
count++;
else
count=1;
if(count == maxCount)
res.push_back(cur->val);
if(count > maxCount){
maxCount = count;
// 清空res
res.clear();
res.push_back(cur->val);
}
pre = cur;
// 右
traversal2(cur->right);
}
vector<int> findMode(TreeNode* root) {
// 法2 双指针法
if(root == NULL ) return res;
traversal2(root);
return res;
}
};