|
2 | 2 |
|
3 | 3 | /**
|
4 | 4 | *261. Graph Valid Tree
|
5 |
| - *Given n nodes labeled from 0 to n - 1 and a list of undirected edges |
| 5 | + * |
| 6 | + * Given n nodes labeled from 0 to n - 1 and a list of undirected edges |
6 | 7 | * (each edge is a pair of nodes),
|
7 | 8 | * write a function to check whether these edges make up a valid tree.
|
8 | 9 |
|
|
24 | 25 | */
|
25 | 26 | public class _261 {
|
26 | 27 |
|
27 |
| - public boolean validTree(int n, int[][] edges) { |
28 |
| - int[] nums = new int[n]; |
29 |
| - for (int i = 0; i < n; i++) { |
30 |
| - nums[i] = i; |
31 |
| - } |
| 28 | + public static class Solution1 { |
| 29 | + public boolean validTree(int n, int[][] edges) { |
| 30 | + int[] nums = new int[n]; |
| 31 | + for (int i = 0; i < n; i++) { |
| 32 | + nums[i] = i; |
| 33 | + } |
| 34 | + |
| 35 | + for (int i = 0; i < edges.length; i++) { |
| 36 | + int x = find(nums, edges[i][0]); |
| 37 | + int y = find(nums, edges[i][1]); |
32 | 38 |
|
33 |
| - for (int i = 0; i < edges.length; i++) { |
34 |
| - int x = find(nums, edges[i][0]); |
35 |
| - int y = find(nums, edges[i][1]); |
| 39 | + if (x == y) { |
| 40 | + return false; |
| 41 | + } |
36 | 42 |
|
37 |
| - if (x == y) { |
38 |
| - return false; |
| 43 | + //union |
| 44 | + nums[x] = y; |
39 | 45 | }
|
40 | 46 |
|
41 |
| - //union |
42 |
| - nums[x] = y; |
| 47 | + return edges.length == n - 1; |
43 | 48 | }
|
44 | 49 |
|
45 |
| - return edges.length == n - 1; |
46 |
| - } |
47 |
| - |
48 |
| - int find(int[] nums, int i) { |
49 |
| - if (nums[i] == i) { |
50 |
| - return i; |
| 50 | + int find(int[] nums, int i) { |
| 51 | + if (nums[i] == i) { |
| 52 | + return i; |
| 53 | + } |
| 54 | + return find(nums, nums[i]); |
51 | 55 | }
|
52 |
| - return find(nums, nums[i]); |
53 | 56 | }
|
54 | 57 | }
|
0 commit comments