↻one more pass.
Graphs · Medium

Graph Valid Tree: the idea to remember.

Decide whether n labeled vertices and undirected edges form a tree.

The source exercise may require LeetCode Premium. This original explanation and Java reference are free to use here.
Solve on LeetCode ↗

The core insight

Require exactly n minus one edges, then traverse from one vertex and check that all vertices are reached.

Why it works

A connected undirected graph with n vertices and n minus one edges has no cycle, so connectivity plus the edge count is sufficient.

The mistake to avoid

The input has n >= 1. An edge count check alone does not prove connectivity.

Time: O(V + E)Space: O(V + E)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

boolean validTree(int n, int[][] edges) {
    if (edges.length != n - 1) return false;
    List<List<Integer>> graph = new ArrayList<>();
    for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
    for (int[] e : edges) { graph.get(e[0]).add(e[1]); graph.get(e[1]).add(e[0]); }
    boolean[] seen = new boolean[n];
    Deque<Integer> stack = new ArrayDeque<>(); stack.push(0); seen[0] = true;
    int reached = 0;
    while (!stack.isEmpty()) {
        int node = stack.pop(); reached++;
        for (int next : graph.get(node)) if (!seen[next]) { seen[next] = true; stack.push(next); }
    }
    return reached == n;
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.