13-line C++ O(n) DFS+Hashing Solution with Comments


  • 0
    class Solution {
    public:
        unordered_map<int, int> mem; // sum to frequency table
        vector<int> res;
        int max=1; // highest frequency
        vector<int> findFrequentTreeSum(TreeNode* root) {
            if(root) calcSum(root);
            return res;
        }
        
        int calcSum(TreeNode* p) { // recursively calculate sum of each node
            int sum = p->val + (p->left?calcSum(p->left):0) + (p->right?calcSum(p->right):0);
            if(++mem[sum]>=max) {
                if(mem[sum]>max) res.clear();
                max=mem[sum];
                res.push_back(sum);
            }
            return sum;
        }
    };
    

Log in to reply
 

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