

Solution 1: check if loop exist
class Solution {
public boolean validTree(int n, int[][] edges) {
Map<Integer, List<Integer>> graph = new HashMap<>();
for (int i = 0; i < n; i++) {
graph.put(i, new ArrayList<>());
}
for (int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
graph.get(edge[1]).add(edge[0]);
}
Queue<Integer> queue = new LinkedList<>();
queue.offer(0);
Set<Integer> visited = new HashSet<>();
visited.add(0);
Map<Integer, Integer> parent = new HashMap<>();
parent.put(0, -1);
while (!queue.isEmpty()) {
int cur = queue.poll();
visited.add(cur);
for (int neighbour : graph.get(cur)) {
parent.put(neighbour, cur);
if (parent.get(cur) == neighbour) {
continue;
}
if (visited.contains(neighbour)) {
return false;
}
queue.offer(neighbour);
}
}
return visited.size() == n;
}
}
Solution 2: Using graph property
- Check whether or not there are
n - 1 edges. If there's not, then return false.
- Check whether or not the graph is fully connected. Return true if it is, false if otherwise.
class Solution {
public boolean validTree(int n, int[][] edges) {
if (edges.length != n - 1) {
return false;
}
Map<Integer, List<Integer>> graph = new HashMap<>();
for (int i = 0; i < n; i++) {
graph.put(i, new ArrayList<>());
}
for (int[] edge : edges) {
graph.get(edge[0]).add(edge[1]);
graph.get(edge[1]).add(edge[0]);
}
Queue<Integer> queue = new LinkedList<>();
queue.offer(0);
Set<Integer> visited = new HashSet<>();
visited.add(0);
while (!queue.isEmpty()) {
int cur = queue.poll();
for (int neighbour : graph.get(cur)) {
if (visited.contains(neighbour)) {
continue;
}
visited.add(neighbour);
queue.offer(neighbour);
}
}
return visited.size() == n;
}
}