C++ using map and multi map


  • 0
    F
    int genSum(TreeNode* node, unordered_map<int, int> &sumFreq, unordered_multimap<int, int> &freqSum, int &mostFreq)
    {
        if(node == NULL) return 0;
        int leftSum = genSum(node->left, sumFreq, freqSum, mostFreq);
        int rightSum = genSum(node->right, sumFreq, freqSum, mostFreq);
        int treeSum = leftSum + rightSum + node->val;
        sumFreq[treeSum] += 1;
        pair<int,int> fs(sumFreq[treeSum], treeSum);
        freqSum.insert(fs);
        mostFreq = (sumFreq[treeSum] > mostFreq) ? sumFreq[treeSum] : mostFreq;
        return treeSum;
    }
    
    vector<int> findFrequentTreeSum(TreeNode* root) {
        unordered_map<int, int> sumFreq;
        unordered_multimap<int, int> freqSum;
        int mostFreq = 0;
        genSum(root, sumFreq, freqSum, mostFreq);
        auto range = freqSum.equal_range(mostFreq);
        vector<int> ans;
        for(auto it = range.first; it != range.second; ++it) {
            ans.push_back(it->second);
        }
        return ans;
    }

Log in to reply
 

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