Graph Valid Tree(union find)
Notice
public class Solution {
/*
* @param n: An integer
* @param edges: a list of undirected edges
* @return: true if it's a valid tree, or false
*/
int[] father;
int find(int x){
if(x == father[x]){
return x;
}
return father[x] = find(father[x]);
}
public boolean validTree(int n, int[][] edges) {
if (n - 1 != edges.length) {
return false;
}
father = new int[n];
for(int i = 0; i < n; i ++){
father[i] = i;
}
for(int[] e : edges){
int root1 = find(e[0]);
int root2 = find(e[1]);
if(root1 == root2){
return false;
}
father[root1] = root2;
}
return true;
}
}Last updated