1.501. 二叉搜索树中的众数 - 力扣(LeetCode)
2.与二叉树的最近公共祖先极其类似,就是将左支右支的判断条件改成了二叉搜索树的性质
/**
* 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:
unordered_map<int,int>map1;
bool static cmp(const pair<int, int>& a, const pair<int, int>& b) {
if (a.second == b.second) {
return a.first < b.first;
}
return a.second > b.second;
}
void set(TreeNode*root)
{
if(root==nullptr)
{
return;
}
map1[root->val]++;
set(root->left);
set(root->right);
}
vector<int> findMode(TreeNode* root) {
set(root);
vector<pair<int,int>>ve(map1.begin(),map1.end());
sort(ve.begin(),ve.end(),cmp);
vector<int>ret;
for(auto t:ve)
{
if(t.second==ve[0].second)
{
ret.push_back(t.first);
}
}
return ret;
}
};