题目:501. 二叉搜索树中的众数
给定一个有相同值的二叉搜索树(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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
基本思想1:dfs+map统计次数
空间复杂度不满足进阶的要求,并且未用上该树是二叉搜索树这个特征。
/**
* 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> m;
vector<int> findMode(TreeNode* root) {
preorder(root);
vector<int> res;
int cnt = 0;
for(auto t : m){
if(t.second > cnt){
res.clear();
res.push_back(t.first);
cnt = t.second;
}
else if(t.second == cnt){
res.push_back(t.first);
}
}
return res;
}
void preorder(TreeNode* root){
if(root){
m[root->val]++;
preorder(root->left);
preorder(root->right);
}
}
};
基本思想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 {
public:
vector<int> res;
int max_cnt = 0;
vector<int> findMode(TreeNode* root) {
int cnt = 0, pre = INT_MIN;
inorder(root, cnt, pre);
return res;
}
void inorder(TreeNode* root, int &cnt, int &pre){
if(root){
inorder(root->left, cnt, pre);
if(root->val == pre){
++cnt;
}
else{
cnt = 1;
}
if(cnt > max_cnt){
max_cnt = cnt;
res.clear();
res.push_back(root->val);
}
else if(cnt == max_cnt){
res.push_back(root->val);
}
pre = root->val;
inorder(root->right, cnt, pre);
}
}
};