-
Notifications
You must be signed in to change notification settings - Fork 112
/
Solution.java
65 lines (48 loc) · 1.54 KB
/
Solution.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
import java.util.HashMap;
import java.util.Map;
/**
* @author Oleg Cherednik
* @since 03.06.2019
*/
public class Solution {
public static void main(String... args) {
System.out.println(findMostFrequentSubtreeSum(createTree())); // 2
}
private static Node createTree() {
Node five = new Node(5);
five.left = new Node(2);
five.right = new Node(-5);
return five;
}
public static int findMostFrequentSubtreeSum(Node root) {
Map<Integer, Integer> sumCount = new HashMap<>();
getSubtreeSum(root, sumCount);
return findMostFrequentKey(sumCount);
}
private static int getSubtreeSum(Node node, Map<Integer, Integer> sumCount) {
if (node == null)
return 0;
int sumLeft = getSubtreeSum(node.left, sumCount);
int sumRight = getSubtreeSum(node.right, sumCount);
int sum = sumLeft + sumRight + node.val;
sumCount.put(sum, sumCount.getOrDefault(sum, 0) + 1);
return sum;
}
private static int findMostFrequentKey(Map<Integer, Integer> sumCount) {
if (sumCount.isEmpty())
return 0;
int res = sumCount.keySet().iterator().next();
for (int sum : sumCount.keySet())
if (sumCount.get(sum) > sumCount.get(res))
res = sum;
return res;
}
public static final class Node {
private final int val;
private Node left;
private Node right;
public Node(int val) {
this.val = val;
}
}
}