- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1361.java
52 lines (50 loc) · 1.71 KB
/
_1361.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
packagecom.fishercoder.solutions.secondthousand;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
publicclass_1361 {
publicstaticclassSolution1 {
publicbooleanvalidateBinaryTreeNodes(intn, int[] leftChild, int[] rightChild) {
int[] indegree = newint[n];
for (inti = 0; i < n; i++) {
if (leftChild[i] >= 0) {
indegree[leftChild[i]]++;
}
if (rightChild[i] >= 0) {
indegree[rightChild[i]]++;
}
}
// only one node has in-degree = 0
intindegreeZero = 0;
for (intnum : indegree) {
if (num == 0) {
indegreeZero++;
if (indegreeZero > 1) {
returnfalse;
}
}
// every other node's in-degree must be exactly equal to 1
if (num > 1) {
returnfalse;
}
}
// no bi-directional pointing
Map<Integer, List<Integer>> map = newHashMap<>();
for (inti = 0; i < n; i++) {
map.put(i, newArrayList<>());
map.get(i).add(leftChild[i]);
map.get(i).add(rightChild[i]);
}
for (intnode : map.keySet()) {
List<Integer> children = map.get(node);
for (intchild : children) {
if (map.containsKey(child) && map.get(child).contains(node)) {
returnfalse;
}
}
}
returntrue;
}
}
}