您的位置:首页 > 其它

LeetCode Graph Valid Tree

2016-03-03 11:27 106 查看
原题链接在这里: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相似.

若是数先判断 边的数量是不是 n-1.

然后判断有没有环,若是find(edge[0],edge[1])返回true 说明edge[0], edge[1]两个点之前就连在一起了.

Time Complexity: O(n*logn). Space: O(n).

AC Java:

public class Solution {
int [] parent;
int [] size;

public boolean validTree(int n, int[][] edges) {
if(n < 0 || edges == null || edges.length != n-1){
return false;
}
parent = new int
;
size = new int
;
for(int i = 0; i<n ;i++){
parent[i] = i;
size[i] = 1;
}

for(int [] edge : edges){
if(!find(edge[0], edge[1])){
union(edge[0], edge[1]);
}else{
return false;
}
}
return true;
}

private 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;
}
private void union(int p, int q){
int i = root(p);
int j = root(q);
if(size[i] < size[j]){
parent[i] = j;
size[j] += size[i];
}else{
parent[j] = i;
size[i] += size[j];
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: