Graph Valid Tree

Difficulty: Medium

You're given n nodes labeled 0 to n - 1 and a list of undirected edges. Return whether they form a valid tree: every node reachable from every other, with no cycles.

Examples

Input: n = 5, edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
Output: true

Every node is connected, with exactly one path between any two nodes and no cycles.

Input: n = 5, edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
Output: false

Nodes 1, 2, and 3 form a cycle (1-2, 2-3, 1-3), so this isn't a tree even though every node is reachable.

Input: n = 4, edges = [[0, 1], [2, 3]]
Output: false

There's no cycle, but the graph is split into two disconnected pieces, so it isn't one single tree.

Constraints

  • 1 <= n <= 2000

  • 0 <= edges.length <= 5000

  • There are no self-loops or duplicate edges.

Approach

Shortcut first: a tree with n nodes has exactly n - 1 edges. Any other count means it's not a tree.

A matching count isn't proof on its own. A small cycle in one place plus a disconnected node elsewhere can also add up to n - 1 edges. So confirm no cycles and fully connected.

Union-Find checks both. Start with every node in its own group and union each edge's endpoints. If they're already in the same group, the edge creates a cycle, so return false. If every edge merges cleanly and there were n - 1 edges, everything ended up in one group: connected and acyclic, a valid tree.

Solutions

DFS Traversal

Check the edge count is n - 1. Then run one DFS from node 0, never walking straight back along the edge you came from (edges are undirected). If the DFS reaches every node without revisiting any, it's a valid tree.

function validTree(n, edges) {
  if (edges.length !== n - 1) return false;

  const graph = Array.from({ length: n }, () => []);
  for (const [a, b] of edges) {
    graph[a].push(b);
    graph[b].push(a);
  }

  const visited = new Set();

  function dfs(node, parent) {
    if (visited.has(node)) return false; // revisiting means a cycle
    visited.add(node);

    for (const neighbor of graph[node]) {
      if (neighbor === parent) continue; // don't walk back along the edge we came from
      if (!dfs(neighbor, node)) return false;
    }
    return true;
  }

  return dfs(0, -1) && visited.size === n;
}

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

Optimal - Union-Find

After checking the edge count is n - 1, union each edge's endpoints. An edge between two nodes already in the same group is a cycle, so it's not a tree. If every edge merges cleanly, the graph is acyclic and (with that edge count) fully connected.

function validTree(n, edges) {
  if (edges.length !== n - 1) return false;

  const parent = Array.from({ length: n }, (_, i) => i);

  function find(x) {
    if (parent[x] !== x) parent[x] = find(parent[x]);
    return parent[x];
  }

  for (const [a, b] of edges) {
    const rootA = find(a);
    const rootB = find(b);
    if (rootA === rootB) return false; // cycle

    parent[rootA] = rootB;
  }

  return true;
}

Time: O(n × α(n)) - nearly O(n) · Space: O(n)