LeetCode501. 二叉搜索树中的众数
题目描述
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
样例
给定 BST [1,null,2,2],
1
\
2
/
2
返回[2].
提示:如果众数超过1个,不需考虑输出顺序
进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-mode-in-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
算法
树的递归与非递归遍历
时空分析
时间复杂度: 树的节点中序遍历一遍,时间复杂度 O(n)
空间复杂度: 开辟了map来存放中序遍历结果,空间复杂度 O(n)
way1:
/**
* 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:
unordered_map<int, int> map_;
vector<int> findMode(TreeNode* root) {
vector<int> res;
dfs(root);
int max = -1;
for(auto i : map_) {
if(i.second > max)
max = i.second;
}
for(auto i: map_) {
if (i.second == max)
res.push_back(i.first);
}
return res;
}
void dfs(TreeNode *root)
{
if (nullptr == root)
return;
dfs(root->left);
++map_[root->val];
dfs(root->right);
}
};
way2: 改进way1对map进行2次遍历
class Solution {
public:
int max = 0;
vector<int> findMode(TreeNode* root)
{
vector<int> ans;
vector<pair<int, int>> v;
inOrder(root, v);
for(int i = 0; i < v.size(); i++)
{
if(v[i].second == max)
{
ans.push_back(v[i].first);
}
}
return ans;
}
void inOrder(TreeNode *root, vector<pair<int, int>> &v)
{
if(root == NULL) return;
inOrder(root->left, v);
if(v.size() == 0) v.push_back(pair<int, int>(root->val, 1));
if(v[v.size() - 1].first != root->val) v.push_back(pair<int, int>(root->val, 1));
if(v[v.size() - 1].first == root->val) v[v.size() - 1].second += 1;
max = max > v[v.size() - 1].second ? max : v[v.size() - 1].second;
inOrder(root->right, v);
}
};
way3: 不使用额外的空间(假设由递归产生的隐式调用栈的开销不被计算在内)
class Solution {
public:
vector<int> findMode(TreeNode* root) {
//如果要求不让使用额外的空间
if(root == nullptr)
return {};
vector<int> res;
stack<TreeNode*> tree;
int max_num = 0; //出现次数最多的数字
int max_times = 0;//出现次数最多数字的出现次数
int cur_times = 0; //当前数字出现的次数
//当前的数字
int cur_num = INT_MAX;
while(!tree.empty() || root != nullptr){
while(root){
tree.push(root);
root = root->left;
}
root = tree.top();
tree.pop();
if(root->val == cur_num){
cur_times++;
if(cur_times == max_times){
res.push_back(root->val);
}
else if(cur_times > max_times){
res.clear();
res.push_back(root->val);
max_times = cur_times;
}
}
else{
cur_times = 1;
cur_num = root->val;
if(cur_times == max_times){
res.push_back(root->val);
}
else if(cur_times > max_times){
res.clear();
res.push_back(root->val);
max_times = cur_times;
}
}
root = root->right;
}
return res;
}
};