二叉搜索树
既然是搜索树,它中序遍历就是有序的。
501.二叉搜索树中的众数
给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
如果树中有不止一个众数,可以按 任意顺序 返回。
假定 BST 满足如下定义:
结点左子树中所含节点的值 小于等于 当前节点的值
结点右子树中所含节点的值 大于等于 当前节点的值
左子树和右子树都是二叉搜索树

如果是有序数组,那么只要比较相邻的数,若一样,count+1;不一样,count=1。
而在二叉搜索树中,其中序遍历就相当于一个有序数组,利用这一点,可以写出以下框架。
BST(cur->left);//左 ......//中,比较并处理两数 BST(cur->right);//右
那么,怎么对二叉树中序遍历呢?答:利用cur和pre两个指针。
而且初始化的时候pre = NULL,这样当pre为NULL时候,我们就知道这是比较的第一个元素。
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int maxCount=0;
int count=0;
TreeNode* pre=nullptr;
vector<int> res;
void BST(TreeNode* cur){
if(cur==nullptr) return;
BST(cur->left);
if(pre!=nullptr&&pre->val==cur->val){
count++;
}
else{
count=1;
}
pre=cur;
if(count==maxCount){
res.push_back(cur->val);
}
if(count>maxCount){
res.clear();
res.push_back(cur->val);
maxCount=count;
}
BST(cur->right);
return;
}
public:
vector<int> findMode(TreeNode* root) {
BST(root);
return res;
}
};
如果不是二叉搜索树,那么就需要用map来统计频率了。
同时要用pair,来对value进行排序,写出判断两数value大小的函数。
总体代码如下:
class Solution {
private:
void searchBST(TreeNode* cur, unordered_map<int, int>& map) { // 前序遍历
if (cur == NULL) return ;
map[cur->val]++; // 统计元素频率
searchBST(cur->left, map);
searchBST(cur->right, map);
return ;
}
bool static cmp (const pair<int, int>& a, const pair<int, int>& b) {
return a.second > b.second;
}
public:
vector<int> findMode(TreeNode* root) {
unordered_map<int, int> map; // key:元素,value:出现频率
vector<int> result;
if (root == NULL) return result;
searchBST(root, map);
vector<pair<int, int>> vec(map.begin(), map.end());
sort(vec.begin(), vec.end(), cmp); // 给频率排个序
result.push_back(vec[0].first);
for (int i = 1; i < vec.size(); i++) {
// 取最高的放到result数组中
if (vec[i].second == vec[0].second) result.push_back(vec[i].first);
else break;
}
return result;
}
};

暂无评论