Short 15 ms C++ solution


  • 0
    P
    class Solution {
    public:
        vector<int> result;
        unordered_map<int, int> lookup;
        int frequent(TreeNode *root)
        {
            if(root==NULL)
                return 0;
            int sum = root->val + frequent(root->left) + frequent(root->right);
            lookup[sum]++;
            return sum;
            
        }
        vector<int> findFrequentTreeSum(TreeNode* root) {
            frequent(root);
            int max=INT_MIN;
            for(auto it=lookup.begin();it!=lookup.end();++it)
                if(it->second>max)
                    max=it->second;
            for(auto it=lookup.begin();it!=lookup.end();++it)
                if(it->second==max)
                    result.push_back(it->first);
            return result;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.