-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNodeAverageSum.java
More file actions
47 lines (33 loc) · 1022 Bytes
/
NodeAverageSum.java
File metadata and controls
47 lines (33 loc) · 1022 Bytes
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
package Trees;
public class NodeAverageSum {
static int count = 0;
static Pair<Integer, Integer> postOrder(Node root) {
if (root == null) return new Pair<>(0, 0);
Pair<Integer, Integer> left = postOrder(root.left);
Pair<Integer, Integer> right = postOrder(root.right);
int nodeSum = left.getKey() + right.getKey() + root.val;
int nodeCount = left.getValue() + right.getValue() + 1;
if (root.val == nodeSum / (nodeCount)) count++;
return new Pair<>(nodeSum, nodeCount);
}
public static int averageOfSubtree(Node root) {
postOrder(root);
return count;
}
public static void main(String[] args) {
}
public static class Pair<T, D> {
T key;
D value;
public Pair(T key, D value) {
this.key = key;
this.value = value;
}
public T getKey() {
return key;
}
public D getValue() {
return value;
}
}
}