Skip to content

Commit f0798d1

Browse files
committedSep 30, 2016
body of graph valid tree
1 parent f1cf5cf commit f0798d1

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
 

‎MEDIUM/src/medium/GraphValidTree.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,31 @@
11
package medium;
22

3+
import java.util.Arrays;
4+
35
/**
46
* Created by fishercoder1534 on 9/29/16.
57
*/
68
public class GraphValidTree {
9+
10+
public boolean validTree(int n, int[][] edges){
11+
int[] nums = new int[n];
12+
Arrays.fill(nums, -1);
13+
14+
for(int i = 0; i < edges.length; i++){
15+
int x = find(nums, edges[i][0]);
16+
int y = find(nums, edges[i][1]);
17+
18+
if(x == y) return false;
19+
20+
//union
21+
nums[x] = y;
22+
}
23+
24+
return edges.length == n-1;
25+
}
26+
27+
int find(int[] nums, int i){
28+
if(nums[i] == -1) return i;
29+
return find(nums, nums[i]);
30+
}
731
}

0 commit comments

Comments
 (0)