Formatted question description: https://leetcode.ca/all/508.html

508. Most Frequent Subtree Sum

Level

Medium

Description

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 occur once.

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

Solution

Do breadth first search and find the parent node of each node. Then loop over all nodes in the reversing order, and add each node’s value to its parent’s value. After this process, all nodes’ values become the subtree sums of the nodes. Find the most frequent subtree sums, obtain the subtree sums that are most frequent, and return.

  • /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int[] findFrequentTreeSum(TreeNode root) {
            if (root == null)
                return new int[0];
            List<TreeNode> nodesList = new ArrayList<TreeNode>();
            Map<TreeNode, TreeNode> childParentMap = new HashMap<TreeNode, TreeNode>();
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                TreeNode node = queue.poll();
                nodesList.add(node);
                TreeNode left = node.left, right = node.right;
                if (left != null) {
                    childParentMap.put(left, node);
                    queue.offer(left);
                }
                if (right != null) {
                    childParentMap.put(right, node);
                    queue.offer(right);
                }
            }
            int maxCount = 0;
            Map<Integer, Integer> sumCountMap = new HashMap<Integer, Integer>();
            for (int i = nodesList.size() - 1; i >= 0; i--) {
                TreeNode node = nodesList.get(i);
                TreeNode parent = childParentMap.get(node);
                if (parent != null)
                    parent.val += node.val;
                int value = node.val;
                int count = sumCountMap.getOrDefault(value, 0);
                count++;
                maxCount = Math.max(maxCount, count);
                sumCountMap.put(value, count);
            }
            List<Integer> frequentSumsList = new ArrayList<Integer>();
            Set<Integer> valuesSet = sumCountMap.keySet();
            for (int value : valuesSet) {
                int count = sumCountMap.getOrDefault(value, 0);
                if (count == maxCount)
                    frequentSumsList.add(value);
            }
            int length = frequentSumsList.size();
            int[] frequentSums = new int[length];
            for (int i = 0; i < length; i++)
                frequentSums[i] = frequentSumsList.get(i);
            return frequentSums;
        }
    }
    
  • // OJ: https://leetcode.com/problems/most-frequent-subtree-sum/
    // Time: O(logN)
    // Space: O(N)
    class Solution {
    public:
        vector<int> findFrequentTreeSum(TreeNode* root) {
            vector<int> ans;
            int maxFreq = 0;
            unordered_map<int, int> m;
            function<int(TreeNode*)> dfs = [&](TreeNode *root) {
                if (!root) return 0;
                int left = dfs(root->left), right = dfs(root->right), sum = left + right + root->val, f = ++m[sum];
                if (f > maxFreq) maxFreq = f, ans = {sum};
                else if (f == maxFreq) ans.push_back(sum);
                return sum;
            };
            dfs(root);
            return ans;
        }
    };
    
  • # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
      def findFrequentTreeSum(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
    
        def helper(root, d):
          if not root:
            return 0
          left = helper(root.left, d)
          right = helper(root.right, d)
          subtreeSum = left + right + root.val
          d[subtreeSum] = d.get(subtreeSum, 0) + 1
          return subtreeSum
    
        d = {}
        helper(root, d)
        mostFreq = 0
        ans = []
        for key in d:
          if d[key] > mostFreq:
            mostFreq = d[key]
            ans = [key]
          elif d[key] == mostFreq:
            ans.append(key)
        return ans
    
    

All Problems

All Solutions