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.
Divide and Conquer
Time Complexity
遍历了一遍树用了O(N), 遍历了一遍hashmap用了O(N), 遍历了一遍arraylist,用了O(N)
O(N)
Space Complexity
hashmap O(N) + arraylist O(N)
O(N)
思路
这题中分治法的运用在于对于每一个节点都是left.val + right.val加上自己的val。
这题更像是考怎么使用hashmap的,建立一个hashmap, key是每个节点的左右子树加上自己的sum,value是这个sum出现的频率,重点要helper函数中keep一个maxCount来记录最高的频率。
这里的Ouput要求是一个int[], 因为array是immutable的,所以我们首先要确定这个array的size,因为一开始没有办法确定,这里先建立了一个arraylist, 先遍历一遍hashmap,找出maxcCount一共有多少个,知道size后,再把arraylist中的数字放入最终的int[] res。
代码
private int maxCount = 0; // count of the most freuqent sum
public int[] findFrequentTreeSum(TreeNode root) {
//Key: sum of the all leftsubtree value + all rightsubtreevalue + root.val
//Value: the count of the frequency of this sum
Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();
helper(root,countMap);
List<Integer> list = new ArrayList<Integer>();
for(int key : countMap.keySet()){
if(countMap.get(key) == maxCount){
list.add(key);
}
}
int[] res = new int[list.size()];
for(int i = 0; i < list.size(); i++){
res[i] = list.get(i);
}
return res;
}
private int helper(TreeNode root, Map<Integer, Integer> countMap){
if(root == null) return 0;
int left = helper(root.left, countMap);
int right = helper(root.right, countMap);
int sum = left + right + root.val;
int count = countMap.getOrDefault(sum, 0) + 1;
countMap.put(sum, count);
maxCount = Math.max(maxCount, count);
return sum;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。