-
Notifications
You must be signed in to change notification settings - Fork 481
/
1361.java
34 lines (32 loc) · 1.09 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
class Solution {
public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {
int[] d = new int[n];
for (int i : leftChild) if (i != -1) d[i]++;
for (int i : rightChild) if (i != -1) d[i]++;
int root = -1;
for (int i = 0; i < n; i++) {
if (d[i] == 0) {
if (root != -1) return false;
root = i;
}
}
if (root == -1) return false;
Set<Integer> vis = new HashSet();
Queue<Integer> q = new LinkedList();
vis.add(root); q.add(root);
while (!q.isEmpty()) {
int pre = q.poll();
if (leftChild[pre] != -1) {
if (vis.contains(leftChild[pre])) return false;
vis.add(leftChild[pre]);
q.add(leftChild[pre]);
}
if (rightChild[pre] != -1) {
if (vis.contains(rightChild[pre])) return false;
vis.add(rightChild[pre]);
q.add(rightChild[pre]);
}
}
return vis.size() == n;
}
}