Posted on

Description

Submission

/**
 * 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 {
    map<int, int> freq;
    int most_freq;
    int dfs(TreeNode* root) {
        if(!root) return 0;
        int sum = dfs(root->left) + dfs(root->right) + root->val;
        freq[sum]++;
        most_freq = max(most_freq, freq[sum]);
        return sum;
    }
public:
    vector<int> findFrequentTreeSum(TreeNode* root) {
        most_freq = 0;
        dfs(root);
        
        vector<int> rets;
        for(auto x: freq) {
            if(x.second == most_freq) {
                rets.push_back(x.first);
            }
        }
        return rets;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *