class Solution {
public:
vector<int> res;
int cnt=0;
int find(TreeNode* root,int val)//返回当前子树值为val的个数
{
if(!root) return 0;
return find(root->left,val)+find(root->right,val)+(val==root->val);
}
map<int,int> hashtable;
void dfs(TreeNode* root)//返回当前子树的众数
{
if(!root) return;
if(!hashtable[root->val])
{
hashtable[root->val]=find(root,root->val);
if(hashtable[root->val]>=cnt)
{
if(hashtable[root->val]>cnt)
res.clear();
cnt=hashtable[root->val];
res.push_back(root->val);
}
}
dfs(root->left);dfs(root->right);
}
vector<int> findMode(TreeNode* root) {
dfs(root);
return res;
}
};
标签:cnt,return,val,树中,find,hashtable,众数,root,LeetCode
From: https://www.cnblogs.com/tangxibomb/p/17454608.html