Most Frequent Subtree Sum

​Given the root of a tree, you are asked to find the most frequent subtree sum. 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). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.

Examples 1

Input:

   5
 /   \
2    -3

return [2, -3, 4], since all the values happen only once, return all of them in any order.

Examples 2

Input:

   5
 /   \
2    -5

Return [2], since 2 happens twice, however, -5 only occurs once.

  • The tree with root 5 has a sum of 2 = (5+2-5) = 2.
  • The tree with root 2 has a sum of 2.

Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer. 

Use a HashMap count to count the subtree sum occurrence. A sub-function dfs(TreeNode node) will travel through a tree, recursively calculate the sum of the subtree, increment the count, and finally, return the sum of the subtree.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    
    int max_count = 0;
    Map<Integer, Integer> sumCountMap = new HashMap<>();
    
    public int[] findFrequentTreeSum(TreeNode root) {
        DFS(root);
        List<Integer> result = new ArrayList<>();
        for(int cur_sum : sumCountMap.keySet()){
            int cur_count = sumCountMap.get(cur_sum);
            if(cur_count == max_count){
                result.add(cur_sum);
            }
        }
        return result.stream().mapToInt(i -> i).toArray();
    }
    
    private int DFS(TreeNode node){
        if(node == null){
            return 0;
        }
        int sum = node.val + DFS(node.left) + DFS(node.right);
        int count = sumCountMap.getOrDefault(sum, 0);
        count += 1;
        sumCountMap.put(sum, count);
        max_count = Math.max(max_count, count);
        return sum;
    }
}

Categories: Binary Tree

Tagged as:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s