题目描述:
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
例如:
给定 BST [1,null,2,2],
返回[2].
提示:如果众数超过1个,不需考虑输出顺序
进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)
方法1:
主要思路:
(1)直观的想,就是直接遍历一遍树,统计各个结点的值出现的次数,并保留一个出现的最大次数,然后在最后的保留的统计中,找出满足要求的数字;
/**
* 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 helper(TreeNode* root,unordered_map<int,int>& mp,int& count){
if(root==NULL){
return;
}
++mp[root->val];//统计数值出现的频率
//保留最高的频率
count=max(count,mp[root->val]);
helper(root->left,mp,count);
helper(root->right,mp,count);
}
vector<int> findMode(TreeNode* root) {
unordered_map<int,int> mp;//保留统计数据
int count=0;
helper(root,mp,count);
vector<int> res;
for(auto& it:mp){//找出满足要求的数字
if(it.second==count){
res.push_back(it.first);
}
}
return res;
}
};