Graph Valid Tree
Thoughts
Code
class Solution {
class UnionFind {
int[] father;
int size;
UnionFind(int n) {
father = new int[n];
for (int i = 0; i < n; i++) {
father[i] = i;
}
size = n;
}
public void union(int x, int y) {
x = find(x);
y = find(y);
if (x == y) {
return;
}
father[x] = y;
size--;
}
public int find(int x) {
if (x == father[x]) {
return x;
}
father[x] = find(father[x]);
return father[x];
}
}
public boolean validTree(int n, int[][] edges) {
UnionFind uf = new UnionFind(n);
for (int[] edge : edges) {
if (uf.find(edge[0]) == uf.find(edge[1])) {
return false;
}
uf.union(edge[0], edge[1]);
}
return uf.size == 1;
}
}Analysis
Last updated