508. Most Frequent Subtree Sum
Given the root
of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.
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).
Example 1:
Input: root = [5,2,-3]
Output: [2,-3,4]
Example 2:
Input: root = [5,2,-5]
Output: [2]
题目:给定一个二叉树,找出所有出现次数最多的子树和的值
思路:DFS,用一个hashmap来保存所有字数和出现的次数,代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int getSum(TreeNode* node, unordered_map<int, int>& m, int& maxFre){
if(!node) return 0;
int left = getSum(node->left, m, maxFre);
int right = getSum(node->right, m, maxFre);
int sum = node->val + left + right;
m[sum]++;
if(m[sum] > maxFre) maxFre = m[sum];
return sum;
}
vector<int> findFrequentTreeSum(TreeNode* root) {
unordered_map<int, int> m;
int maxFre = 0;
getSum(root, m, maxFre);
vector<int> res;
for(auto mp : m){
if(mp.second == maxFre)
res.push_back(mp.first);
}
return res;
}
};
还没有评论,来说两句吧...