Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than or equal to the node’s key.
The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
Both the left and right subtrees must also be binary search trees.
For example:
Given BST [1,null,2,2],
1
2
/
2
return [2].
Note: If a tree has more than one mode, you can return them in any order.
Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
中文:给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
方法1:中序遍历二叉树,利用哈希表记录值与其相应的次数,返回 次数最多对应的值即可。(需要维护一个变量mx来记录当前最多的次数值,这样在遍历完树之后,根据这个mx值就能把对应的元素找出来)
class Solution {
public:
vector<int> findMode(TreeNode* root) {
if(!root) return {};
vector<int> res;
unordered_map<int,int> m;
int mx=0;
TreeNode *p=root;
stack<TreeNode*> s;
while(p||!s.empty()){
while(p){
s.push(p);
p=p->left;
}
p=s.top();
s.pop();
mx = max(mx,++m[p->val]);
p=p->right;
}
for(auto a:m){
if(a.second == mx){
res.push_back(a.first);
}
}
return res;
}
};
语法:
1.遍历哈希表(或其他vector容器)的简便写法
for(auto a:m)
方法2(不使用额外的空间):利用二叉树的性质,中序遍历二叉树即可得到有序的结果。指针pre来记录上一个遍历到的结点,mx记录最大的次数,cnt来计数当前元素出现的个数。
代码:
class Solution {
public:
vector<int> findMode(TreeNode* root) {
if (!root) return {};
vector<int> res;
TreeNode *p = root, *pre = NULL;
stack<TreeNode*> s;
int mx = 0, cnt = 1;;
while (!s.empty() || p) {
while (p) {
s.push(p);
p = p->left;
}
p = s.top(); s.pop();
if (pre) { //当前结点不是第一个结点
cnt = (p->val == pre->val) ? cnt + 1 : 1;
}
if (cnt >= mx) { //更新mx值
if (cnt > mx) res.clear();
res.push_back(p->val);
mx = cnt;
}
pre = p;
p = p->right;
}
return res;
}
};
还可以用递归的写法
class Solution {
public:
vector<int> findMode(TreeNode* root) {
vector<int> res;
int mx=0,cnt=1;
TreeNode *pre=NULL;
inorder(root,pre,cnt,mx,res);
return res;
}
void inorder(TreeNode *node,TreeNode* &pre,int& cnt,int& mx,vector<int> &res){
if(!node) return;
inorder(node->left,pre,cnt,mx,res);
if(pre){
cnt=(node->val==pre->val)? cnt+1:1;
}
if(cnt>=mx){
if(cnt>mx) res.clear();
res.push_back(node->val);
mx=cnt;
}
pre=node;
inorder(node->right,pre,cnt,mx,res);
}
};