C++ AC Solution 22ms


  • 0
    A
    /**
     * 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 {
    public:
        map<int,int> freq;
        int mx;
        int recur(TreeNode *tree)
        {
            if(tree==NULL)
                return 0;
            int sum = tree->val + recur(tree->left) + recur(tree->right);
            freq[sum]++;
            mx = max(freq[sum],mx);
            return sum;
        }
        vector<int> findFrequentTreeSum(TreeNode* root) {
            freq.clear();
            mx = -1;
            recur(root);
            int i,j;
            vector<int> ans;
            ans.resize(0);
            for(auto xx : freq)
                {
                    if(xx.second == mx)
                        ans.push_back(xx.first);
                }
            return ans;
        }
    };
    

Log in to reply
 

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