Graph Valid Tree (LeetCode 261): Solution and Explanation

Medium
Depth First Search
Breadth First Search
Union Find
Graph

Given n nodes labeled 0 to n - 1 and a list of undirected edges, decide whether those edges form a valid tree. A valid tree connects every node and contains no cycles.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A tree has two defining properties: it is connected, and it has no cycles. Checking both is the whole problem. A useful sanity check is that a tree on n nodes always has exactly n - 1 edges, so many solutions reject any other edge count immediately, but edge count alone is not enough since a cycle plus a disconnected node can still have n - 1 edges.

DFS handles both properties in one traversal. Start at node 0 and explore. If the search ever arrives at a node it has already visited, there is a second route to that node, which means a cycle. After the search finishes, if the visited set does not contain all n nodes, some node was unreachable, so the graph is not connected.

The subtle part is that undirected edges appear in both directions in the adjacency list. When you step from node 0 to node 1, node 1's neighbor list includes 0, and revisiting it would look like a cycle even though you are just looking back along the edge you came from. Passing the parent prev into each call and skipping it solves this. Because the input has no repeated edges, skipping the parent never hides a real cycle.

Approach: DFS cycle detection plus connectivity

  1. If n is 0, return true. Otherwise build an adjacency list, adding each edge in both directions.
  2. Create an empty visit set and define dfs(i, prev).
  3. If i is already in visit, a cycle exists, so return false.
  4. Add i to visit, then recurse into every neighbor j except prev. If any call returns false, propagate false.
  5. Return true from the DFS if no cycle was found.
  6. The graph is a tree when dfs(0, -1) is true and len(visit) == n.

Step-by-step example

n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
  1. Adjacency: 0 to [1,2,3], 1 to [0,4], 2 to [0], 3 to [0], 4 to [1].
  2. dfs(0, -1) visits 0 and calls dfs(1, 0), which visits 1, skips its parent 0, and calls dfs(4, 1).
  3. dfs(4, 1) visits 4. Its only neighbor is the parent 1, so it returns true, and so does dfs(1, 0).
  4. Back at 0, dfs(2, 0) and dfs(3, 0) each visit their node, skip the parent, and return true.
  5. The DFS returns true and visit = {0,1,2,3,4} has size 5, so the answer is true. Adding edge [2,3] would make dfs(3, 2) reach 0 again, which is already visited, and return false.

Code: Python, Java, C++

1class Solution:
2    def validTree(self, n: int, edges: List[List[int]]) -> bool:
3        if not n:
4            return True
5        adj = { i:[] for i in range(n) }
6        for n1, n2 in edges:
7            adj[n1].append(n2)
8            adj[n2].append(n1)
9            
10        visit = set()
11        
12        def dfs(i, prev):
13            if i in visit:
14                return False
15            
16            visit.add(i)
17            for j in adj[i]:
18                if j == prev:
19                    continue
20                if not dfs(j, i):
21                    return False
22            return True
23            
24        return dfs(0, -1) and n == len(visit)

Time and space complexity

Time

O(n + E)

Building the adjacency list touches each edge twice, and the DFS visits each node once and scans each adjacency entry once.

Space

O(n + E)

The adjacency list stores 2E entries, the visited set holds up to n nodes, and the recursion can be n levels deep on a path-shaped graph.

Other approaches

Union-find with an edge count check (time O(n + E × α(n)), space O(n))

First return false unless there are exactly n - 1 edges. Then union every edge; if any edge connects two nodes that already share a root, there is a cycle. With n - 1 edges and no cycle, the graph must be connected.

BFS with a parent map (time O(n + E), space O(n + E))

Same idea as the DFS but iterative, storing each node's parent so the back edge can be ignored. It avoids recursion depth limits on long chains.

Common mistakes

  • Not skipping the parent, so every undirected edge looks like a cycle and the answer is always false once there is an edge.
  • Checking only for cycles and forgetting connectivity. Two separate trees have no cycles but are not a single tree.
  • Relying only on the n - 1 edge count, which misses a graph with one cycle and one isolated node.
  • Hitting the recursion limit in Python on a long chain of 2,000 nodes. Raise the limit or use an iterative traversal if that is a concern.

Frequently asked questions

How do you know if a graph is a valid tree?

It must be connected and acyclic. Equivalently, it has exactly n - 1 edges and is connected, or exactly n - 1 edges and no cycles. Any two of the three properties imply the third.

Why do we pass the previous node in the DFS?

In an undirected graph each edge appears in both nodes' neighbor lists. Without skipping the node you came from, the DFS would immediately see it as already visited and report a false cycle.

Is union-find or DFS better for graph valid tree?

Both are effectively linear. Union-find with the n - 1 edge check is compact and needs no adjacency list, while DFS is easier to explain and reuses common traversal code.