forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidate Binary Tree Nodes.java
58 lines (54 loc) · 1.25 KB
/
Validate Binary Tree Nodes.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
import java.util.Arrays;
class Solution {
static class UF {
int[] parents;
int size;
UF(int n) {
parents = new int[n];
size = n;
Arrays.fill(parents, -1);
}
int find(int x) {
if (parents[x] == -1) {
return x;
}
return parents[x] = find(parents[x]);
}
boolean union(int a, int b) {
int pA = find(a), pB = find(b);
if (pA == pB) {
return false;
}
parents[pA] = pB;
size--;
return true;
}
boolean connected() {
return size == 1;
}
}
public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {
UF uf = new UF(n);
int[] indeg = new int[n];
for (int i = 0; i < n; i++) {
int l = leftChild[i], r = rightChild[i];
if (l != -1) {
/**
* i: parent node
* l: left child node
* if i and l are already connected or the in degree of l is already 1
*/
if (!uf.union(i, l) || ++indeg[l] > 1) {
return false;
}
}
if (r != -1) {
// Same thing for parent node and the right child node
if (!uf.union(i, r) || ++indeg[r] > 1) {
return false;
}
}
}
return uf.connected();
}
}