C++ Solution - Easy to understand


  • 0
    unordered_map<int,int> umap;
    int recur(TreeNode *root)
    {
        if(root == NULL)
            return 0;
        int sum = root->val;
        sum += recur(root->left);
        sum += recur(root->right);
        
        if(umap.find(sum) == umap.end())
            umap[sum] = 1;
        else
            umap[sum]++;
      
        return sum;
    }
    bool static compare(const pair<int,int> &p1,const pair<int,int> &p2)
    {
        return p1.second > p2.second;
    }
    vector<int> findFrequentTreeSum(TreeNode* root) {
        umap.clear();
        vector<int> ans;
        if(!root)
            return ans;
        recur(root);
        vector<pair<int,int> > vec(umap.begin(),umap.end());
        sort(vec.begin(),vec.end(),compare);
        ans.push_back(vec[0].first);
        int max = vec[0].second;
        for(int i=1;i<vec.size();i++)
        {
            if(vec[i].second == max)
                ans.push_back(vec[i].first);
            else
                break;
        }
        return ans;
    }
    

    };


Log in to reply
 

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