原题链接在这里: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:
1 public class Solution { 2 public boolean validTree(int n, int[][] edges) { 3 if(edges == null || edges.length != n-1){ 4 return false; 5 } 6 7 UnionFind tree = new UnionFind(n); 8 for(int [] edge : edges){ 9 if(!tree.find(edge[0], edge[1])){ 10 tree.union(edge[0], edge[1]); 11 }else{ 12 return false; 13 } 14 } 15 return true; 16 } 17 } 18 19 class UnionFind{ 20 int count, n; 21 int [] size; 22 int [] parent; 23 24 public UnionFind(int n){ 25 this.n = n; 26 this.count = n; 27 size = new int[n]; 28 parent = new int[n]; 29 for(int i = 0; i<n; i++){ 30 parent[i] = i; 31 size[i] = 1; 32 } 33 } 34 35 public boolean find(int i, int j){ 36 return root(i) == root(j); 37 } 38 39 private int root(int i){ 40 while(i != parent[i]){ 41 parent[i] = parent[parent[i]]; 42 i = parent[i]; 43 } 44 return i; 45 } 46 47 public void union(int p, int q){ 48 int i = root(p); 49 int j = root(q); 50 if(size[i] > size[j]){ 51 parent[j] = i; 52 size[i] += size[j]; 53 }else{ 54 parent[i] = j; 55 size[j] += size[i]; 56 } 57 this.count--; 58 } 59 60 public int size(){ 61 return this.count; 62 } 63 }