508. Most Frequent Subtree Sum

Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.

Examples 1
Input:

``````  5
/  \
2   -3
``````

return [2, -3, 4], since all the values happen only once, return all of them in any order.

Examples 2
Input:

``````  5
/  \
2   -5
``````

return [2], since 2 happens twice, however -5 only occur once.

Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.

``````class Solution {
public:
vector<int> findFrequentTreeSum(TreeNode* root) {
vector<int> res;
unordered_map<int, int> m;
int cnt = 0;
postorder(root, m, cnt, res);
return res;
}
int postorder(TreeNode* node, unordered_map<int, int>& m, int& cnt, vector<int>& res) {
if (!node) return 0;
int left = postorder(node->left, m, cnt, res);
int right = postorder(node->right, m, cnt, res);
int sum = left + right + node->val;
++m[sum];
if (m[sum] >= cnt) {
if (m[sum] > cnt) res.clear();
res.push_back(sum);
cnt = m[sum];
}
return sum;
}
};
``````

``````class Solution {
public:
vector<int> findFrequentTreeSum(TreeNode* root) {
vector<int> res;
unordered_map<int, int> m;
int cnt = 0;
postorder(root, m, cnt);
for (auto a : m) {
if (a.second == cnt) res.push_back(a.first);
}
return res;
}
int postorder(TreeNode* node, unordered_map<int, int>& m, int& cnt) {
if (!node) return 0;
int left = postorder(node->left, m, cnt);
int right = postorder(node->right, m, cnt);
int sum = left + right + node->val;
cnt = max(cnt, ++m[sum]);
return sum;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/508

Subtree of Another Tree

https://leetcode.com/problems/most-frequent-subtree-sum/

https://leetcode.com/problems/most-frequent-subtree-sum/discuss/98675/JavaC%2B%2BPython-DFS-Find-Subtree-Sum

https://leetcode.com/problems/most-frequent-subtree-sum/discuss/98664/Verbose-Java-solution-postOrder-traverse-HashMap-(18ms)

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation