题意
给一个BST,求val值的众数(可能有多个)
follow up:能否只用 O(1) 空间呢?(二叉树遍历过程中的栈空间不计入)
思路
算法1
O(n) 时间, O(n) 空间
遍历二叉树,并且用一个vis[]
数组来记录每个数出现了多少次。为了避免vis[]
太大爆内存,可用unordered_map
替代
算法2
O(n) 时间, O(1) 空间
我们知道BST一个很重要的性质就是:其中序遍历结果是一个升序数组
对一个有序数组,求他的众数我们只需要遍历2遍统计结果即可
该题也只需要先对BST中序遍历一遍求出众数对应的出现次数是多少,再遍历一遍去统计结果即可
代码
算法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 {
private:
unordered_map<int, int> vis;
vector<int> ans;
int _max = 0;
public:
void dfs(TreeNode* root) {
if (!root) return;
vis[root->val]++;
if (vis[root->val] > _max) _max = vis[root->val];
dfs(root->left);
dfs(root->right);
}
vector<int> findMode(TreeNode* root) {
_max = 0;
dfs(root);
for (auto it = vis.begin(); it != vis.end(); it++) {
if (it->second == _max) ans.push_back(it->first);
}
return ans;
}
};
算法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 {
private:
int max_;
int pre, count;
bool flag;
vector<int> ans;
void reset() {
flag = 0;
count = 0;
}
void cal(int x, int sta) {
if (!flag) {
if (!sta) max_ = 1;
pre = x;
count++;
if (sta && count == max_) ans.push_back(x);
flag = true;
} else {
if (pre == x) {
count++;
if (!sta && count > max_) max_ = count;
if (sta && count == max_) ans.push_back(x);
} else {
count = 1;
pre = x;
if (sta && count == max_) ans.push_back(x);
}
}
}
void inorder(TreeNode* root, int sta) {
if (!root) return;
inorder(root->left, sta);
cal(root->val, sta);
inorder(root->right, sta);
}
public:
Solution() : max_(0), pre(-1), count(0), flag(false) {}
vector<int> findMode(TreeNode* root) {
inorder(root, 0);
reset();
inorder(root, 1);
return ans;
}
};