-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMost_Frequent_Subtree_Sum.cpp
More file actions
44 lines (43 loc) · 1.24 KB
/
Copy pathMost_Frequent_Subtree_Sum.cpp
File metadata and controls
44 lines (43 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# number : 508
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> findFrequentTreeSum(TreeNode* root) {
vector<int> result;
int maxNumber = 0;
if (root == NULL)
return result;
int temp = sumOfNode(root);
map<int, int>::iterator it;
for (it = mp.begin(); it != mp.end(); it++)
if (it->second > maxNumber)
maxNumber = it->second;
for (it = mp.begin(); it != mp.end(); it++)
if (it->second == maxNumber)
result.push_back(it->first);
return result;
}
int sumOfNode(TreeNode* root) {
int sum = 0;
if (root->left == NULL && root->right == NULL)
sum = root->val;
else if (root->left == NULL)
sum = sumOfNode(root->right) + root->val;
else if (root->right == NULL)
sum = sumOfNode(root->left) + root->val;
else
sum = sumOfNode(root->left) + sumOfNode(root->right) + root->val;
mp[sum] += 1;
return sum;
}
private:
map<int, int> mp;
};