My solution to LeetCode problem Most Frequent Subtree Sum works, but I have several questions regarding the code. I am also looking for an advice on how to improve the code.
Problem:
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.
Example 1
5 / \ 2 -3
return [2, -3, 4], since all the values happen only once, return all of them in any order
Example 2
5 / \ 2 -5
return [2], since 2 happens twice, however -5 only occur once
My questions:
The function
get_sums_freqs
returns anint
, but when I call it, I do not assign the result to anything:get_sums_freqs (root, sum_freqs);
. Is it ok to do it this way?For some reason, it feels like a bad style to me to initialize the hash map
unordered_map<int, int> sum_freqs;
in one function and then pass it to another function to fill it out. Is there a better way to do it? Or is this a correct way?
My solution:
vector<int> find_frequent_tree_sum(TreeNode* root) {
// Collect freqs of sums into map
unordered_map<int, int> sum_freqs;
get_sums_freqs (root, sum_freqs);
// Get the max freq
int max_freq = 0;
unordered_map<int, int>::iterator it;
for (it = sum_freqs.begin(); it != sum_freqs.end(); ++it) {
max_freq = max(max_freq, it->second);
}
// Collect all the values, which freq == max_freq
vector<int> res;
//unordered_map<int, int>::iterator it;
for (it = sum_freqs.begin(); it != sum_freqs.end(); ++it) {
if (it->second == max_freq) {
res.push_back(it->first);
}
}
return res;
}
int get_sums_freqs (TreeNode* root, unordered_map<int, int>& sum_freqs) {
if (root) {
int curr_sum = root->val +
get_sums_freqs (root->left, sum_freqs) +
get_sums_freqs (root->right, sum_freqs);
sum_freqs[curr_sum]++;
return curr_sum;
} else {
return 0;
}
}
For context, here's the definition of TreeNode given by LeetCode:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};