LeetCode Graph Valid Tree

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Graph Valid Tree相关的知识,希望对你有一定的参考价值。

原题链接在这里: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 }

 

以上是关于LeetCode Graph Valid Tree的主要内容,如果未能解决你的问题,请参考以下文章

Graph Valid Tree -- LeetCode

Leetcode 261: Graph Valid Tree

Leetcode 261: Graph Valid Tree

leetcode 261-Graph Valid Tree(medium)(BFS, DFS, Union find)

[LintCode] Graph Valid Tree

Graph Valid Tree