public boolean validTree2(int n, int[][] edges) {
        HashMap<Integer, ArrayList<Integer>> list = new HashMap<Integer, ArrayList<Integer>>();
        for (int i = 0; i < n; ++i) list.put(i, new ArrayList<Integer>());
        for (int[] edge : edges) {
            list.get(edge[0]).add(edge[1]);
            list.get(edge[1]).add(edge[0]);
        }

        LinkedList<Integer> q = new LinkedList<Integer>();
        boolean[] visited = new boolean[n];
        q.add(0);
        while (!q.isEmpty()) {
            int node = q.remove();
            if (visited[node]) return false; // detect cycles
            visited[node] = true;
            for (int next : list.get(node)) {
                if (!visited[next]) {
                    q.add(next);
                }
            }
        }
        for (int i = 0; i < n; ++i) {
            if (!visited[i]) return false; // detect islands
        }
        return true;
    }