对二叉树进行遍历,对每个值都进行对比,相等的就count++,不相等就将count重新置1,重新计数,然后把值存在容器中,
class Solution {
private:
int maxcount=0;//最大频率
int count=0;//统计频率
TreeNode* pre=NULL;
vector<int>result;
void searchBST(TreeNode* cur)
{
if(cur==NULL)return;
searchBST(cur->left);
if(pre==NULL)
{count=1;}
else if(pre->val==cur->val)
{count++;}
else{count=1;}
pre=cur;
if(count==maxcount)result.push_back(cur->val);
if(count>maxcount)
{
maxcount=count;
result.clear();
result.push_back(cur->val);
}
searchBST(cur->right);
return;
}
public:
vector<int> findMode(TreeNode* root) {
count=0;
maxcount=0;
pre=NULL;
result.clear();
searchBST(root);
return result;
}
};