Description
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.
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).
Solution 1(C++)
static int x=[](){std::ios::sync_with_stdio(false); cin.tie(NULL); return 0; }();
class Solution {
public:
void travel(TreeNode* node){
if(!node) return;
mode[node->val]++;
travel(node->right);
travel(node->left);
}
vector<int> findMode(TreeNode* root) {
travel(root);
vector<int> res;
for(auto iter=mode.begin(); iter!=mode.end(); iter++){
if(!res.size()) res.push_back(iter->first);
else{
if(iter->second > mode[res[0]]){
res.clear(); res.push_back(iter->first);
}
else if(iter->second == mode[res[0]]) res.push_back(iter->first);
else continue;
}
}
return res;
}
private:
map<int, int> mode;
};
Solution 2(C++)
class Solution {
public:
vector<int> findMode(TreeNode* root) {
vector<int>res;
TreeNode* pre= NULL;
int gmax = INT_MIN;
int cnt=0;
helper(root,res,pre,cnt, gmax);
return res;
}
void helper(TreeNode* root, vector<int>& res, TreeNode* &pre, int &cnt, int &gmax){
if(!root) return;
helper(root->left,res,pre,cnt,gmax);
if(pre!= NULL){
cnt = pre->val == root->val ? cnt+1: 1;
}
else
cnt++;
if(cnt >= gmax ){
if(cnt > gmax) res.clear();
res.push_back(root->val);
gmax = cnt;
}
pre = root;
helper(root->right,res,pre,cnt,gmax);
}
};
算法分析
解法一,暴力解法。解法二,比较符合题目的要求。但目前还没有看太懂。
现在明白了,这就是利用二叉树的中序遍历的方法,将BST转换成一个排序好的数组。可参考:二叉树前序、中序、后序遍历的迭代实现。
二叉树的三种遍历方法真的非常经典,我准备单独用一篇博客来学习一下。到时候也会在这篇博客中进行更新。
程序分析
略。