In this Leetcode Most Frequent Subtree Sum problem solution Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.

The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).

Leetcode Most Frequent Subtree Sum problem solution


Problem solution in Python.

class Solution:
    def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:
        hash = {}
        
        # Traversal DFS
        def getSum(node):
            if node is not None:
                leftSum = getSum(node.left)
                rightSum = getSum(node.right)
                total =  leftSum + node.val + rightSum
                if total in hash:
                    hash[total] +=1
                else:
                    hash[total] = 1
                return total
            else:
                return 0
        getSum(root)
        
        # Find the outputs
        max_l = max(hash.values())
        return [key for key, val in hash.items() if val == max_l]

Problem solution in Java.

class Solution {
    public HashMap<Integer,Integer> hm=new HashMap<>();
    public int[] findFrequentTreeSum(TreeNode root) {
       int max=0;
        
       helper(root);
       for(int i:hm.keySet()){
           max=Math.max(max,hm.get(i));
       }
       List<Integer> ls=new ArrayList<>();
        for(int i:hm.keySet()){
           if(hm.get(i)==max)
               ls.add(i);
       }
        int[] a=new int[ls.size()];
        for(int i=0;i<a.length;i++)
            a[i]=ls.get(i);
        
        return a;
        
    }
    public int helper(TreeNode root){
        if(root==null){
            return 0;
        }
        int val=helper(root.left)+helper(root.right)+root.val;
        hm.put(val,hm.getOrDefault(val,0)+1);
        return val; 
    }
}


Problem solution in C++.

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;
    }  
};