Skip to content

Commit bfb5f6c

Browse files
solves #261: Graph Valid Tree in java
1 parent 042c845 commit bfb5f6c

File tree

2 files changed

+60
-1
lines changed

2 files changed

+60
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@
225225
| 258 | [Add Digits](https://leetcode.com/problems/add-digits) | [![Java](assets/java.png)](src/AddDigits.java) [![Python](assets/python.png)](python/add_digits.py) | |
226226
| 259 | 🔒 [3Sum Smaller](https://leetcode.com/problems/3sum-smaller) | | |
227227
| 260 | [Single Number III](https://leetcode.com/problems/single-number-iii) | [![Java](assets/java.png)](src/SingleNumberIII.java) | |
228-
| 261 | 🔒 [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree) | | |
228+
| 261 | 🔒 [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree) | [![Java](assets/java.png)](src/GraphValidTree.java) | |
229229
| 263 | [Ugly Number](https://leetcode.com/problems/ugly-number) | [![Java](assets/java.png)](src/UglyNumber.java) [![Python](assets/python.png)](python/ugly_number.py) | |
230230
| 264 | [Ugly Number II](https://leetcode.com/problems/ugly-number-ii) | [![Java](assets/java.png)](src/UglyNumberII.java) | |
231231
| 266 | 🔒 [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation) | | |

src/GraphValidTree.java

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// https://leetcode.com/problems/graph-valid-tree
2+
// T: O(N)
3+
// S: O(N)
4+
5+
public class GraphValidTree {
6+
private static final class DisjointSet {
7+
private final int[] root, rank;
8+
9+
public DisjointSet(int size) {
10+
root = new int[size];
11+
rank = new int[size];
12+
for (int i = 0 ; i < size ; i++) {
13+
root[i] = i;
14+
rank[i] = 1;
15+
}
16+
}
17+
18+
public int find(int num) {
19+
if (root[num] == num) {
20+
return num;
21+
}
22+
return root[num] = find(root[num]);
23+
}
24+
25+
public boolean areConnected(int x, int y) {
26+
return find(x) == find(y);
27+
}
28+
29+
public void union(int x, int y) {
30+
final int rootX = find(x), rootY = find(y);
31+
if (rootX == rootY) {
32+
return;
33+
}
34+
if (root[rootX] < root[rootY]) {
35+
root[rootX] = rootY;
36+
} else if (root[rootX] > root[rootY]) {
37+
root[rootY] = rootX;
38+
} else {
39+
root[rootY] = rootX;
40+
rank[rootX]++;
41+
}
42+
}
43+
}
44+
45+
public boolean validTree(int n, int[][] edges) {
46+
if (edges.length != n - 1) {
47+
return false;
48+
}
49+
50+
final DisjointSet disjointSet = new DisjointSet(n);
51+
for (int[] edge : edges) {
52+
if (disjointSet.areConnected(edge[0], edge[1])) {
53+
return false;
54+
}
55+
disjointSet.union(edge[0], edge[1]);
56+
}
57+
return true;
58+
}
59+
}

0 commit comments

Comments
 (0)