1361. Validate Binary Tree Nodes

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
class Solution {
public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {
int[] inDegrees = new int[n];
for (int i = 0; i < n; i++) {
int from = i;
int left = leftChild[i], right = rightChild[i];
if (left != -1 && ++inDegrees[left] > 1) {
return false;
}
if (right != -1 && ++inDegrees[right] > 1) {
return false;
}
}

Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (inDegrees[i] == 0) {
queue.offer(i);
}
}
if (queue.size() != 1) {
return false;
}

int nodeCount = 0;
while (!queue.isEmpty()) {
int node = queue.poll();
nodeCount++;
int left = leftChild[node];
if (left != -1) {
queue.offer(left);
}
int right = rightChild[node];
if (right != -1) {
queue.offer(right);
}
}

return nodeCount == n;
}
}

References

1361. Validate Binary Tree Nodes