# Java 2 solutions, union-find & dfs

• Union Find Method:

``````    public boolean validTree_UnionFind(int n, int[][] edges) {
int[] uf = new int[n];
for(int i=0; i<n; i++) {
uf[i] = i;
}
for(int[] edge : edges){
if(union(edge[0], edge[1], uf) == false)
return false;
}
Set<Integer> set = new HashSet<>();
for(int i=0; i<n; i++){
}
return set.size() == 1;
}
private boolean union(int node1, int node2, int[] uf){
int x = find(node1, uf);
int y = find(node2, uf);
if(x==y) return false;
uf[x] = y;
return true;
}
private int find(int node, int[] uf){
if(uf[node] == node) return node;
uf[node] = find(uf[node], uf);
return uf[node];
}
``````

DFS Method:

``````    public boolean validTree_dfs(int n, int[][] edges) {
if(n==1 && edges.length==0) return true;
if(edges.length==0) return false;
for(int i=0; i<n; i++)
for(int[] edge : edges){
}
Set<Integer> set = new HashSet<>();
boolean res = isTree_dfs(edges[0][0], adj, set, null);
if(set.size() != n) return false;
return res;
}
private boolean isTree_dfs(Integer root, List<Integer>[] adj, Set<Integer> set, Integer parent) {
if(set.contains(root)) return false;