Skip to content

Instantly share code, notes, and snippets.

@s4553711
Created April 21, 2018 13:54
Show Gist options
  • Save s4553711/a6ffc40d267fd62ffc3bc5a16c855704 to your computer and use it in GitHub Desktop.
Save s4553711/a6ffc40d267fd62ffc3bc5a16c855704 to your computer and use it in GitHub Desktop.
/**
* 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) {
unordered_map<int, int> freqs;
int max_freq = -1;
vector<int> ans;
(void)treeSum(root, freqs, max_freq, ans);
return ans;
}
int treeSum(TreeNode* root, unordered_map<int, int>& freqs, int& max_freq, vector<int>& ans) {
if (!root) return 0;
int sum = root->val +
treeSum(root->left, freqs, max_freq, ans) +
treeSum(root->right, freqs, max_freq, ans);
int freq = ++freqs[sum];
if (freq > max_freq) {
max_freq = freq;
ans.clear();
}
if (freq == max_freq) {
ans.push_back(sum);
}
return sum;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment