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.

解析
给定一个二叉树,求出现频率最高的子树之和。
解法:postorder
建立一个哈希表,保存子树和以及出现的频率。利用后序遍历,每次记录对当前节点的子树和,并更新频率最大。
class Solution {
public:
vector<int> findFrequentTreeSum(TreeNode* root) {
if(!root) return {};
vector<int> res;
unordered_map<int,int> m;
int mx = 0;
int b = postorder(root, m, mx);
for(auto a : m){
if(a.second == mx){
res.push_back(a.first);
}
}
return res;
}
int postorder(TreeNode* root, unordered_map<int, int>& m, int& mx) {
if(!root) return 0;
int left = postorder(root->left,m,mx);
int right = postorder(root->right,m,mx);
m[right+left+root->val] ++;
mx = max(mx, m[right+left+root->val]);
return right+left+root->val;
}
};
本文介绍了一种在二叉树中寻找出现频率最高的子树和的算法。通过后序遍历,利用哈希表记录每个子树的和及其频率,最终返回频率最高的子树和值。适用于需要解决树形结构数据中最频繁子树和问题的场景。
538

被折叠的 条评论
为什么被折叠?



