c++ solution


  • 0
    Q
    /**
     * 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 {
    private:
        map<TreeNode*, int> mp;
    public:
        vector<int> findFrequentTreeSum(TreeNode* root) {
            int t = get_sum(root), n = 0;
            map<int,int> m;
            vector<int> res;
            for(auto it:mp){
                m[it.second]++;
                n = max(n,m[it.second]);
            }
            for(auto it:m)
                if(it.second == n)
                    res.push_back(it.first);
            return res;
        }
        
        int get_sum(TreeNode* root){
            if(root == nullptr)
                return 0;
            if(mp.find(root) != mp.end())
                return mp[root];
            int res = root->val;
            res += get_sum(root->left) + get_sum(root->right);
            mp[root] = res;
            return res;
        }
        
        
    };
    

Log in to reply
 

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