public class Solution {
public boolean validTree(int n, int[][] edges) {
int[] states = new int[n];
ArrayList[] graph = new ArrayList[n];
for(int i = 0; i < n; i++){
graph[i] = new ArrayList();
}
for(int[] edge : edges){
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
if(hasCycle(-1, 0, states, graph)) return false;
for(int state : states){
if(state == 0) return false;
}
return true;
}
private boolean hasCycle(int prev, int cur, int[] states, ArrayList[] graph){
states[cur] = 1;
boolean hasCycle = false;
for(int i = 0; i < graph[cur].size(); i++){
int next = (int) graph[cur].get(i);
if(next != prev){
if(states[next] == 1) return true;
else if(states[next] == 0){
hasCycle = hasCycle || hasCycle(cur, next, states, graph);
}
}
}
states[cur] = 2;
return hasCycle;
}
}