-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy path33--graph-valid-tree.java
More file actions
38 lines (33 loc) · 1016 Bytes
/
Copy path33--graph-valid-tree.java
File metadata and controls
38 lines (33 loc) · 1016 Bytes
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
public class Solution { // LintCode
public boolean validTree(int n, int[][] edges) {
int[] root = new int[n];
int[] rank = new int[n];
for (int i = 0; i < n; i++) {
root[i] = i;
rank[i] = 0;
}
int count = n; // number of connected components
for (int[] edge : edges) {
int A = edge[0], B = edge[1];
int rootA = find(root, A); // union-find
int rootB = find(root, B);
if (rootA == rootB) return false;
// union
if (rank[rootA] >= rank[rootB]) {
root[rootB] = rootA;
rank[rootA]++;
} else {
root[rootA] = rootB;
raFnk[rootB]++;
}
count--;
}
return (count == 1);
}
public int find(int[] root, int X) {
if (root[X] != X) {
root[X] = find(root, root[X]);
}
return root[X];
}
} // TC: O(V + E), SC: O(V)