C++ recursive count


  • 0
    B
    /**
     * 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:
        vector<int> findFrequentTreeSum(TreeNode* root) {
            int freq = 0;
            unordered_map<int,int>count;
            help(root, count, freq);
            vector<int>ans;
            if(freq > 0)
                for(auto e : count)
                    if(e.second == freq)
                        ans.push_back(e.first);
            return ans;
        }
        
        int help(TreeNode* root, unordered_map<int,int> & count, int & freq)
        {
            if(!root) return 0;
            int left = help(root -> left, count, freq);
            int right = help(root -> right, count, freq);
            int val = root -> val + left + right;
            count[val]++;
            freq = max(freq, count[val]);
            return val;
        }
    };

Log in to reply
 

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