原题链接在这里:https://leetcode.com/problems/graph-valid-tree/
题目:
Given n
nodes labeled from 0
to n - 1
and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
For example:
Given n = 5
and edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
, return true
.
Given n = 5
and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
, return false
.
题解:
Union-Find, 与Number of Islands II相似.
Check is edges count is equal to n-1(There is only one cluster after merging).
然后判断有没有环,若是find(edge[0],edge[1])返回true 说明edge[0], edge[1]两个点之前就连在一起了.
Time Complexity: O(n*logn). Space: O(n).
AC Java:
public class Solution {
public boolean validTree(int n, int[][] edges) {
if(edges == null || edges.length != n-1){
return false;
} UnionFind tree = new UnionFind(n);
for(int [] edge : edges){
if(!tree.find(edge[0], edge[1])){
tree.union(edge[0], edge[1]);
}else{
return false;
}
}
return true;
}
} class UnionFind{
int count, n;
int [] size;
int [] parent; public UnionFind(int n){
this.n = n;
this.count = n;
size = new int[n];
parent = new int[n];
for(int i = 0; i<n; i++){
parent[i] = i;
size[i] = 1;
}
} public boolean find(int i, int j){
return root(i) == root(j);
} private int root(int i){
while(i != parent[i]){
parent[i] = parent[parent[i]];
i = parent[i];
}
return i;
} public void union(int p, int q){
int i = root(p);
int j = root(q);
if(size[i] > size[j]){
parent[j] = i;
size[i] += size[j];
}else{
parent[i] = j;
size[j] += size[i];
}
this.count--;
} public int size(){
return this.count;
}
}