PracticeNeetCode ↗LeetCode ↗
Given n nodes labeled 0 to n - 1 and a list of undirected edges, determine whether these edges form a valid tree — fully connected, with no cycles.
n nodes must have exactly n - 1 edges — more implies a cycle, fewer means it can't possibly be connected. Check this first as a cheap early exit.n nodes.n - 1, return False immediately.True only if all n nodes were visited — the edge-count check already ruled out cycles, so full visitation confirms connectivity.Time: O(V + E) — Space: O(V + E)
def validTree(n: int, edges: list[list[int]]) -> bool:
if len(edges) != n - 1:
return False
graph = {i: [] for i in range(n)}
for a, b in edges:
graph[a].append(b)
graph[b].append(a)
visited = set()
def dfs(node: int, parent: int) -> None:
visited.add(node)
for neighbor in graph[node]:
if neighbor != parent and neighbor not in visited:
dfs(neighbor, node)
dfs(0, -1)
return len(visited) == nHow the solution above works, piece by piece.
n - 1 edges. Any other count → False immediately.not in visited check was missing from the original code on this page, which made it recurse forever when node 0 is on a cycle (e.g. n = 4, edges 0–1, 1–2, 2–0); it's fixed above.Running it on n = 5, edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]:
False before any search. Otherwise a DFS checks that every node is reachable from 0.