标签:
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
.
Hint:
n = 5
and edges = [[0, 1], [1, 2], [3, 4]]
, what should your return? Is this case a valid tree? Note: you can assume that no duplicate edges will appear in edges
. Since all edges are undirected, [0, 1]
is the same as [1, 0]
and thus will not appear together in edges
.
1 public class Solution { 2 public boolean validTree(int n, int[][] edges) { 3 int[] pt = new int[n]; 4 for (int i=0; i<n; i++) { pt[i] = i; } 5 6 for (int[] edge : edges) { 7 int root1 = find(pt, edge[0]); 8 int root2 = find(pt, edge[1]); 9 10 if (root1 == root2) return false; // find circle 11 12 pt[root1] = root2; // union 13 } 14 return edges.length == n-1; // tree w/ n notes have n-1 edges 15 } 16 private int find(int[] pt, int i) { 17 while (pt[i] != i) { 18 pt[i] = pt[pt[i]]; 19 i = pt[i]; 20 } 21 return i; 22 } 23 }
标签:
原文地址:http://www.cnblogs.com/joycelee/p/5310560.html