链接:https://leetcode-cn.com/problems/most-frequent-subtree-sum
给你一个二叉树的根结点,请你找出出现次数最多的子树元素和。一个结点的「子树元素和」定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。
你需要返回出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的子树元素和(不限顺序)。
/**
* 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:
//按照第二个值进行排序
static bool cmp(pair<int,int> &a,pair<int,int> &b){
return a.second > b.second;
}
//后序遍历模板,并且记录值出现的次数
int dfs(TreeNode *root,unordered_map<int,int> &m){
int sum;
if(!root) return 0;
int l = dfs(root->left,m);
int r = dfs(root->right,m);
sum=root->val+r+l;
m[sum]++;
return sum;
}
vector<int> findFrequentTreeSum(TreeNode* root) {
unordered_map<int,int> m;
dfs(root,m);
//map不能使用sort算法,只能将其用vector存储后,再使用sort进行排序
vector<pair<int,int> > v;
for(auto it:m){
v.push_back(it);
}
//按照出现的频率进行排序
sort(v.begin(),v.end(),cmp);
vector<int> res;
if(v.empty()) return res;
res.push_back(v[0].first);
for(int i=1;i<v.size();i++){
if(v[i].second!=v[0].second)
break;
res.push_back(v[i].first);
}
return res;
}
};