class Solution {
public boolean validTree(int n, int[][] edges) {
int[] nums = new int[n];
Arrays.fill(nums, -1);
for (int i = 0; i < edges.length; i++) {
int x = find(nums, edges[i][0]);
int y = find(nums, edges[i][1]);
if (x == y) return false;
nums[x] = y;
}
return edges.length == n - 1;
}
private int find(int[] nums, int i) {
if (nums[i] == -1) return i;
return find(nums, nums[i]);
}
}
DFS with adjList:
class Solution {
public boolean validTree(int n, int[][] edges) {
List<List<Integer>> adjList = new ArrayList<>();
for (int i = 0; i < n; i++)
adjList.add(i, new ArrayList<Integer>());
for (int i = 0; i < edges.length; i++) {
int u = edges[i][0], v = edges[i][1];
adjList.get(u).add(v);
adjList.get(v).add(u);
}
boolean[] visited = new boolean[n];
if (hasCycle(adjList, 0, visited, -1)) return false;
for (int i = 0; i < n; i++) {
if (!visited[i]) return false;
}
return true;
}
public boolean hasCycle(List<List<Integer>> adjList, int u, boolean[] visited, int parent) {
visited[u] = true;
for (int i = 0; i < adjList.get(u).size(); i++) {
int v = adjList.get(u).get(i);
if ((visited[v] && parent != v) || (!visited[v] && hasCycle(adjList, v, visited, u)))
return true;
}
return false;
}
}
Union Find:
DFS with adjList: