Simple C++ solution using a hash map


  • 0
    G
        vector<int> findFrequentTreeSum(TreeNode* root) {
            vector<int> ans;
            unordered_map<int, int> sum_cnts;
            int max_cnt = 0;
            if (root) (void) findTreeSum(root, sum_cnts, &max_cnt);
            else return ans;
    
            for (auto sc : sum_cnts) {
                if (sc.second == max_cnt) ans.push_back(sc.first);
            }
            return ans;
        }
        int findTreeSum(TreeNode* root /*non-null*/, unordered_map<int, int>& sum_cnts, int* max_cnt) {
            int sum = root->val +
                      (root->left ? findTreeSum(root->left, sum_cnts, max_cnt) : 0) +
                      (root->right ? findTreeSum(root->right, sum_cnts, max_cnt) : 0);
            sum_cnts[sum]++;
            *max_cnt = max(*max_cnt, sum_cnts[sum]);
            return sum;
        }
    

Log in to reply
 

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