难度简单257
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
- 结点左子树中所含结点的值小于等于当前结点的值
- 结点右子树中所含结点的值大于等于当前结点的值
- 左子树和右子树都是二叉搜索树
例如:
给定 BST[1,null,2,2]
,1 \ 2 / 2
返回[2]
.提示:如果众数超过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:
vector<int> vals;
vector<int> findMode(TreeNode* root) {
sorted(root);
vector<int> res;
int count = 1;
int maxCount = 1;
int base = vals[0];
res.push_back(vals[0]);
for(int i = 1; i < vals.size(); i++){
if(base == vals[i]){
count ++;
}else{
maxCount = count;
base = vals[i];
count = 1;
}
if(count == maxCount){
res.push_back(vals[i]);
}
if(count > maxCount){
maxCount = count;
res.clear();
res.push_back(vals[i]);
}
}
return res;
}
void sorted(TreeNode* root){
if(root == NULL){
return ;
}
sorted(root->left);
vals.push_back(root->val);
sorted(root->right);
}
};
下面是根据官方题解写的,能够知道这样做比较好,没有用多余的数组,并且在中序遍历时已经调用了update方法对数进行了操作。这样做还是很奇妙的。
/**
* 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:
vector<int> res;
int base, maxCount, count;
vector<int> findMode(TreeNode* root) {
sorted(root);
return res;
}
void sorted(TreeNode* root){
if(root == NULL){
return ;
}
sorted(root->left);
update(root->val);
sorted(root->right);
}
void update(int x){
if (x == base){
count++;
}else{
count = 1;
base = x;
}
if(count == maxCount){
res.push_back(base);
}
if(count >maxCount){
res.clear();
maxCount = count;
res.push_back(base);
}
}
};
这个题目给我的一些想法:
从数组里找到找到重复数最多的值时,update里面先比较最大次数和当前次数,如果一样则是相同的重复数最多,当当前次数大于最大次数时需要更新最大次数,并且将之前的数组清空,放入新的数。
void update(int x){
if (x == base){
count++;
}else{
count = 1;
base = x;
}
if(count == maxCount){
res.push_back(base);
}
if(count >maxCount){
res.clear();
maxCount = count;
res.push_back(base);
}
}