/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int dfs(TreeNode* now,int& mxf,map<int,int>& mp){
int sum = now->val;
if(now->left != NULL) sum += dfs(now->left,mxf,mp);
if(now->right != NULL) sum += dfs(now->right,mxf,mp);
mp[sum]++;
mxf = max(mxf,mp[sum]);
return sum;
}
vector<int> findFrequentTreeSum(TreeNode* root) {
vector<int> ans;
if(root == NULL) return ans;
map<int,int> mp;
int mxf = 1;
dfs(root,mxf,mp);
for(map<int,int>::iterator p=mp.begin();p!=mp.end();p++){
if(p->second == mxf){
ans.push_back(p->first);
}
}
return ans;
}
};
No.102 - LeetCode508
最新推荐文章于 2022-04-22 11:31:24 发布