- 二叉搜索树中的众数
- 思路1:
见到二叉搜索树,就往中序遍历上想;题目要求不能有额外空间,因此放弃用一个数组存储中序遍历的结果再进行处理的方式;因此只能选择在遍历的途中,不断的寻找众数,由于二叉搜索树的中序遍历中,若右相同值,则一定是连续的。因此需要维护一个pre指针方便两两比较,还需要维护两个计数值(一个用于保存当前处理子列的计数值,一个用于保存历史的最大计数值),最后需要一个res数组存结果集合(众数可能不止一个)
难点:我们不知道最终的众数出现的次数到底是几,因此我们只能随着遍历的进行,眼光立足当下,我们只往res中存目前遍历过的结点中的众数,每当更新最大计数值,就代表res中存的值已经不是众数了,就需要把res清空,重新存;
class Solution {
private:
int MaxCount = 0, TempCount = 0;
TreeNode* pre = NULL;
vector<int> res;
void travel(TreeNode* cur){
if(!cur) return;
travel(cur->left);
if(pre == NULL) TempCount = 1;
else if(cur->val == pre->val) ++TempCount;
else TempCount = 1;
if(TempCount > MaxCount){
MaxCount = TempCount;
res.clear();
res.push_back(cur->val);
}
else if(TempCount == MaxCount){
res.push_back(cur->val);
}
pre = cur;
travel(cur->right);
}
public:
vector<int> findMode(TreeNode* root) {
travel(root);
return res;
}
};
class Solution {
private:
int MaxCount = 0, TempCount = 0;
TreeNode* pre = NULL;
vector<int> res;
public:
vector<int> findMode(TreeNode* root) {
if(!root) return res;
stack<TreeNode*> stk;
TreeNode* cur = root;
while(cur || !stk.empty()){
if(cur){
stk.push(cur);
cur = cur->left;
}
else{
cur = stk.top();
stk.pop();
if(pre == NULL) TempCount = 1;
else if(cur->val == pre->val) ++TempCount;
else TempCount = 1;
if(TempCount > MaxCount){
MaxCount = TempCount;
res.clear();
res.push_back(cur->val);
}
else if(TempCount == MaxCount){
res.push_back(cur->val);
}
pre = cur;
cur = cur->right;
}
}
return res;
}
};
- 若本题不是二叉搜索树,则求众数代码如下
核心:C++无法对unordered_map按value排序,只会按key排序,因此需要我们自己指定排序函数
class Solution {
private:
unordered_map<int, int> res;
vector<int> result;
class cmp : public binary_function<pair<int, int>, pair<int, int>, bool>{
public:
bool operator()(const pair<int, int>& a, const pair<int, int>& b){
return a.second > b.second;
}
};
public:
vector<int> findMode(TreeNode* root) {
if(!root) return result;
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty()){
TreeNode* cur = stk.top();
stk.pop();
if(cur){
if(cur->right) st.push(cur->right);
st.push(cur);
st.push(NULL);
if(cur->left) st.push(cur->left);
}
else{
res[stk.top()->val]++;
stk.pop();
}
}
sort(res.begin(), res.end(), cmp());
result.push_back(res[0].first);
for(int i = 1; i < res.size(); ++i){
if(res[i].second == res[0].second) result.push_back(res[i].first);
else break;
}
return result;
}
};
- 总结:
当递归函数,需要找最。值时,如果我们暂时无法知道到底是几,我们就边做边改,出现更好的就抛弃旧的重新来,做一个老渣男;