给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
例如:
给定 BST [1,null,2,2],
1
2
/
2
返回[2].
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void inorder(TreeNode* root, unordered_map<int,int>&m){
if(root==NULL) return;
inorder(root->left,m);
m[root->val]++;//map中key值为root->val的value值加1
inorder(root->right,m);
return;
}
//1.排序知识点!!!
bool static cmp(const pair<int,int>&a,const pair<int,int>&b){
return a.second>b.second;
}
vector<int> findMode(TreeNode* root) {
unordered_map<int,int>m;
vector<int>result;
if(root==NULL)return result;
inorder(root, m);//将map中的所有key值自动排序,并在value中保存了key值出现的频率
//用vecotr容器排序一对数组的知识点!!!
vector<pair<int,int>>v(m.begin(),m.end());//把map从头到尾添加到v中
sort(v.begin(),v.end(),cmp);//按照频率大小排序
result.push_back(v[0].first);
for(int i=1; i<v.size(); i++){
if(v[i].second==v[0].second) result.push_back(v[i].first);
else break;
}
return result;
}
};
// class Solution {
// private:
// void searchBST(TreeNode* cur, unordered_map<int, int>& map) { // 前序遍历
// if (cur == NULL) return ;
// map[cur->val]++; // 统计元素频率
// searchBST(cur->left, map);
// searchBST(cur->right, map);
// return ;
// }
// bool static cmp (const pair<int, int>& a, const pair<int, int>& b) {
// return a.second > b.second;
// }
// public:
// vector<int> findMode(TreeNode* root) {
// unordered_map<int, int> map;
// vector<int> result;
// if (root == NULL) return result;
// searchBST(root, map);
// vector<pair<int, int>> vec(map.begin(), map.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;
// }
// };