给出二叉树的根,找出出现次数最多的子树元素和。一个结点的子树元素和定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。然后求出出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的元素(不限顺序)。
示例 1
输入:
5
/ \
2 -3
返回 [2, -3, 4],所有的值均只出现一次,以任意顺序返回所有值。
示例 2
输入:
5
/ \
2 -5
返回 [2],只有 2 出现两次,-5 只出现 1 次。
来源:力扣(LeetCode)
链接: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:
unordered_map<int, int> iMap;
vector<int> ret;
vector<int> findFrequentTreeSum(TreeNode* root)
{
if(root == NULL)
return ret;
bianli(root);
vector<pair<int, int>> vtMap;
for (auto it = iMap.begin(); it != iMap.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;
});
int times = vtMap.begin()->second;
for (auto it = vtMap.begin(); it != vtMap.end(); it++)
{
if(it->second == times)
{
ret.push_back(it->first);
}
}
return ret;
}
void bianli(TreeNode* root)
{
if(root != NULL)
{
int sum = 0;
qiuhe(root, sum);
//ret.push_back(sum);
iMap[sum]++;
bianli(root->left);
bianli(root->right);
}
}
void qiuhe(TreeNode* root, int& sum)
{
if(root != NULL)
{
sum += root->val;
qiuhe(root->left, sum);
qiuhe(root->right, sum);
}
}
};