题目链接:https://leetcode-cn.com/problems/most-frequent-subtree-sum/
解题步骤:
- 首先,我们需要求每个节点的子树元素和,每个节点的左右子节点的子树元素和就是该节点的子问题,因此,使用递归进行求解
- 求出子树元素和后,还需要计算其出现的次数,使用hashmap存储子树元素和 和 次数的映射关系
- 并通过一个变量记录出现最多的次数max
- 最后遍历hashmap,找出出现次数为max的子树元素和
C++实现:
/**
* 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 {
unordered_map<int, int> map; // 记录子树元素和、出现次数的映射
int maxSum; // 记录最多出现次数
public:
int countSubTreeSum(TreeNode* root) {
if (root == nullptr)
return 0;
int sum = root->val + countSubTreeSum(root->left) + countSubTreeSum(root->right);
if (map.find(sum) != map.end())
map[sum]++;
else
map[sum] = 1;
maxSum = max(maxSum, map[sum]);
return sum;
}
vector<int> findFrequentTreeSum(TreeNode* root) {
countSubTreeSum(root);
vector<int> res;
for (auto& m : map) {
if (m.second == maxSum)
res.push_back(m.first);
}
return res;
}
};