给你一个含重复值的二叉搜索树(BST)的根节点 root
,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
如果树中有不止一个众数,可以按 任意顺序 返回。
假定 BST 满足如下定义:
- 结点左子树中所含节点的值 小于等于 当前节点的值
- 结点右子树中所含节点的值 大于等于 当前节点的值
- 左子树和右子树都是二叉搜索树
class Solution {
private:
int max_count = 0;
int count = 0;
TreeNode* pre = NULL;
vector<int> list;
public:
vector<int> findMode(TreeNode* root) {
if (root == NULL) {
return list;
}
findMode(root->left);
if (pre == NULL) {
count = 1;
}else if(pre->val == root->val) {
count++;
}
else{
count = 1;
}
pre = root;
if (count == max_count) {
list.push_back(root->val);
}
if (count > max_count) {
max_count = count;
list.clear();
list.push_back(root->val);
}
findMode(root->right);
return list;
}
};