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
.
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
.
/*public class Solution {
boolean[] visited;
public boolean validTree(int n, int[][] edges) {
visited = new boolean[n];
List<List<Integer>> lists = new ArrayList<List<Integer>>();
for (int i = 0; i < n; i++) {
lists.add(new ArrayList<Integer>());
}
for (int[] pair: edges) {
lists.get(pair[0]).add(pair[1]);
lists.get(pair[1]).add(pair[0]);
}
if (!helper(lists, 0, -1)) {
return false;
}
for (boolean visit: visited) {
if (!visit) {
return false;
}
}
return true;
}
private boolean helper(List<List<Integer>> lists, int n, int pre) {
if (visited[n] == true) {
return false;
}
visited[n] = true;
for (int curr: lists.get(n)) {
if (curr != pre) {
if (!helper(lists, curr, n)) {
return false;
}
}
}
return true;
}
}*/
public class Solution {
public boolean validTree(int n, int[][] edges) {
int[] roots = new int[n];
Arrays.fill(roots, -1);
for (int[] edge: edges) {
int x = find(roots, edge[0]);
int y = find(roots, edge[1]);
if (x == y) {
return false;
}
roots[x] = y;
}
return edges.length == n - 1;
}
private int find(int[] roots, int n) {
while(roots[n] != -1) {
n = roots[n];
}
return n;
}
}