05 August 2008
Given the
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.1
root
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).
Example 1:
1
2
Input: root = [5,2,-3]
Output: [2,-3,4]
Example 2:
1
2
Input: root = [5,2,-5]
Output: [2]
Constraints:
1
[1, 104]
.1
-105 <= Node.val <= 105
εεΊιε
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* 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 maxCount = 0;
public int[] findFrequentTreeSum(TreeNode root) {
HashMap<Integer, Integer> map = new HashMap<>();
findSum(root, map);
List<Integer> resultList = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() == maxCount) {
resultList.add(entry.getKey());
}
}
// int[] result = new int[resultList.size()];
// for (int i = 0; i < resultList.size(); i++) {
// result[i] = resultList.get(i);
// }
// return result;
return resultList.stream()
.filter(Objects::nonNull)
.mapToInt(Integer::intValue)
.toArray();
}
private int findSum(TreeNode root, HashMap<Integer, Integer> map) {
if (root == null) {
return 0;
}
int sum = findSum(root.left, map) + findSum(root.right, map) + root.val;
int count = map.getOrDefault(sum, 0) + 1;
maxCount = Math.max(maxCount, count);
map.put(sum, count);
return sum;
}
}