Skip to content

Commit ff6c061

Browse files
authored
Create most-frequent-subtree-sum.cpp
1 parent 913cbb6 commit ff6c061

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

C++/most-frequent-subtree-sum.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
vector<int> findFrequentTreeSum(TreeNode* root) {
16+
unordered_map<int,int> counts;
17+
int max_count = 0;
18+
countSubtreeSumsHelper(root, &counts, &max_count);
19+
20+
vector<int> result;
21+
for (const auto& kvp : counts){
22+
if (kvp.second == max_count) {
23+
result.emplace_back(kvp.first);
24+
}
25+
}
26+
return result;
27+
}
28+
29+
private:
30+
int countSubtreeSumsHelper(TreeNode *root, unordered_map<int,int> *counts, int *max_count) {
31+
if (!root) {
32+
return 0;
33+
}
34+
auto sum = root->val +
35+
countSubtreeSumsHelper(root->left, counts, max_count) +
36+
countSubtreeSumsHelper(root->right, counts, max_count);
37+
++(*counts)[sum];
38+
(*max_count) = max((*max_count), (*counts)[sum]);
39+
return sum;
40+
}
41+
};

0 commit comments

Comments
 (0)