261. Graph Valid Tree
// Some code
class Solution {
int[] graph;
int[] size;
int count;
boolean hasCircle;
public boolean validTree(int n, int[][] edges) {
graph = new int[n];
size = new int[n];
for(int i=0; i<graph.length; i++){
graph[i]=i;
size[i]=1;
}
count = n;
for(int[] edge : edges){
union(edge[0], edge[1]);
}
return !hasCircle && count==1;
}
private void union(int p, int q){
int rootP = find(p);
int rootQ = find(q);
if(rootP != rootQ){
if(size[rootP]>size[rootQ]){
graph[rootQ] = rootP;
size[rootP]+=size[rootQ];
}else{
graph[rootP]=rootQ;
size[rootQ]+=size[rootP];
}
count--;
}else{
hasCircle=true;
}
}
private int find(int p){
while(graph[p] != p){
graph[p]=graph[graph[p]];
p=graph[p];
}
return p;
}
}Last updated
Was this helpful?