The key to this problem is using STL map. In order to store the occurrence of each sum, we have to add the sum and its occurrence to the map in every traverse, until the tree is fully gone through. Than we just traverse the map, compare every occurrence in the map with the biggest one, and decide which to push into the vector, finally return it.
class Solution {
public:
vector<int> findFrequentTreeSum(TreeNode* root) {
vector<int> values;
map<int, int> count;
int HighCount = 0;
countSum(root, count, HighCount);
map<int, int> ::iterator it;
for(it=count.begin();it!=count.end();it++){
if(it->second == HighCount) values.push_back(it->first);
}
return values;
}
int countSum(TreeNode* root, map<int, int> &count, int &HighCount){
if(root==NULL)return 0;
int x = root->val;
x += countSum(root->left, count, HighCount);
x += countSum(root->right, count, HighCount);
count[x]++;
HighCount = max(HighCount, count[x]);
return x;
}
};