思路就是二叉树的中序遍历
对于一个二叉搜索树来说,它的中序遍历会是一个排序数组
排序后相同的数都会出现在某一段
class Solution {
public:
int maxSize = 0;
vector<int> findMode(TreeNode* root) {
vector<int> res;
int base = NULL;
int count = NULL;
findModeHelp(root, base, count, res);
return res;
}
void findModeHelp(TreeNode* root, int & base, int & count, vector<int> & res){
if(root == NULL) return;
findModeHelp(root->left, base, count, res);
if(base == NULL && count == NULL){
// cout<<"middle trace initialize: "<<root->val<<endl;
base = root->val;
count = 1;
maxSize = count;
res.push_back(base);
}
else{
// cout<<"middle trace: "<<root->val<<endl;
// cout<<"base: "<<base<<endl;
// cout<<"count: "<<count<<endl;
// cout<<"maxSize: "<<maxSize<<endl;
if(root->val == base) {
count++;
if(count > maxSize){
res.clear();
res.push_back(base);
maxSize = count;
}
else if(count == maxSize){
res.push_back(base);
}
}
else{ // 前一数值结束
base = root->val;
count = 1;
if(count == maxSize) res.push_back(base);
}
}
findModeHelp(root->right, base, count, res);
}
};