Created
April 21, 2018 13:54
-
-
Save s4553711/a6ffc40d267fd62ffc3bc5a16c855704 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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