Most Frequent Subtree Sum
Problem
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
Post-order traversal with HashMap Solution: O(n) time, O(n) space
public class Solution {
int maxCount = 0;
public int[] findFrequentTreeSum(TreeNode root) {
if (root == null) return new int[0];
Map<Integer, Integer> map = new HashMap<>();
postOrder(root, map);
List<Integer> list = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() == maxCount) list.add(entry.getKey());
}
return list.stream().mapToInt(i -> i).toArray();
}
private int postOrder(TreeNode node, Map<Integer, Integer> map) {
if (node == null) return 0;
int left = postOrder(node.left, map);
int right = postOrder(node.right, map);
int sum = left + right + node.val;
int count = map.getOrDefault(sum, 0) + 1;
map.put(sum, count);
maxCount = Math.max(maxCount, count);
return sum;
}
}
Analysis
A typical post-order traversal solution
We have map
with sum as key
and the frequency of sum as value
We can't exchange them because we need to use map.getOrDefault(sum, 0)
in our postOrder()
method
In that method, we get the sum
by adding left + right + node.val
Then we get the frequency of current sum
and put sum, count
into map
Also we need to update the maxCount
After calling the postOrder()
method, we use map.entrySet()
to collect most frequent sum to a list
Then we call list.stream().mapToInt(i -> i).toArray()
to return int[]
result