forked from seanprashad/leetcode-patterns
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path261_Graph_Valid_Tree.java
36 lines (28 loc) · 834 Bytes
/
261_Graph_Valid_Tree.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
classSolution {
publicbooleanvalidTree(intn, int[][] edges) {
int[] parents = newint[n];
for (inti = 0; i < parents.length; i++) {
parents[i] = i;
}
for (int[] edge : edges) {
intp1 = findParent(parents, edge[0]);
intp2 = findParent(parents, edge[1]);
if (p1 == p2) {
returnfalse;
}
union(parents, p1, p2);
--n;
}
returnn == 1;
}
privateintfindParent(int[] parents, intnode) {
if (parents[node] == node) {
returnparents[node];
}
parents[node] = findParent(parents, parents[node]);
returnparents[node];
}
privatevoidunion(int[] parents, intp1, intp2) {
parents[p2] = parents[p1];
}
}