forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMostFrequentSubtreeSum.java
69 lines (52 loc) · 1.48 KB
/
MostFrequentSubtreeSum.java
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
/**
* 这题算法比较直观
*/
public class MostFrequentSubtreeSum {
/**
* key为sum,value为出现的次数
*/
private HashMap<Integer, Integer> mCounts;
/**
* key为次数,value为出现该次数的所有sum
*/
private HashMap<Integer, List<Integer>> mMap;
private int mMaxCount;
public int[] findFrequentTreeSum(TreeNode root) {
if (root == null) {
return new int[0];
}
mCounts = new HashMap<>();
mMap = new HashMap<>();
helper(root);
List<Integer> list = mMap.get(mMaxCount);
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) {
if (root == null) {
return 0;
}
int left = helper(root.left);
int right = helper(root.right);
Integer sum = left + right + root.val;
int count = mCounts.getOrDefault(sum, 0);
mCounts.put(sum, count + 1);
mMaxCount = Math.max(mMaxCount, count + 1);
if (mMap.containsKey(count)) {
mMap.get(count).remove(sum);
}
List<Integer> list = mMap.get(count + 1);
if (list == null) {
list = new LinkedList<>();
mMap.put(count + 1, list);
}
list.add(sum);
return sum;
}
}