给定一颗树的根,请找到的出现频率最高的子树和。 节点的子树和被定义为由以该节点为根的子树(包括节点本身)形成的所有节点值的总和。 那么最常见的子树和值是多少? 如果存在平局,则以任何顺序返回频率最高的所有值。
样例
例1:
输入:
{5,2,-3}
输出:
[-3,2,4]
解释:
5
/ \
2 -3
因为所有的值都只出现了依次,所以可以以任何顺序返回他们。
例2:
输入:
{5,2,-5}
输出:
[2]
解释:
5
/ \
2 -5
因为 2 出现了两次, 而 -5 只出现了一次.
注意事项
你可以假设任何子树的和都在32bit的有符号整数的范围内。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the root
* @return: all the values with the highest frequency in any order
*/
unordered_map<int, int> mymap;
vector<int> findFrequentTreeSum(TreeNode * root)
{
// Write your code here
vector<int> ret;
bianli(root);
vector<pair<int, int>> vtMap;
for (auto it = mymap.begin(); it != mymap.end(); it++)
vtMap.push_back(make_pair(it->first, it->second));
sort(vtMap.begin(), vtMap.end(),
[](const pair<int, int> &x, const pair<int, int> &y) -> int {
return x.second > y.second;
});
//ret.push_back(vtMap.begin()->first);
for (auto it = vtMap.begin(); it != vtMap.end(); it++)
{
if(it->second == vtMap.begin()->second)
{
ret.push_back(it->first);
}
}
return ret;
}
void bianli(TreeNode * root)
{
if(root != NULL)
{
int mysum = sum(root);
mymap[mysum]++;
bianli(root->left);
bianli(root->right);
}
}
int sum(TreeNode * root)
{
if(root == NULL)
return 0;
return sum(root->left) + sum(root->right) + root->val;
}
};