Graph Valid Tree (LeetCode 261): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- If
nis 0, return true. Otherwise build an adjacency list, adding each edge in both directions. - Create an empty
visitset and definedfs(i, prev). - If
iis already invisit, a cycle exists, so return false. - Add
itovisit, then recurse into every neighborjexceptprev. If any call returns false, propagate false. - Return true from the DFS if no cycle was found.
- The graph is a tree when
dfs(0, -1)is true andlen(visit) == n.
Step-by-step example
n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
- Adjacency: 0 to [1,2,3], 1 to [0,4], 2 to [0], 3 to [0], 4 to [1].
dfs(0, -1)visits 0 and callsdfs(1, 0), which visits 1, skips its parent 0, and callsdfs(4, 1).dfs(4, 1)visits 4. Its only neighbor is the parent 1, so it returns true, and so doesdfs(1, 0).- Back at 0,
dfs(2, 0)anddfs(3, 0)each visit their node, skip the parent, and return true. - The DFS returns true and
visit = {0,1,2,3,4}has size 5, so the answer is true. Adding edge [2,3] would makedfs(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)1class Solution {
2 public boolean validTree(int n, int[][] edges) {
3 if (n == 0) return true;
4 List<List<Integer>> adj = new ArrayList<>();
5 for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
6 for (int[] edge : edges) {
7 adj.get(edge[0]).add(edge[1]);
8 adj.get(edge[1]).add(edge[0]);
9 }
10
11 Set<Integer> visit = new HashSet<>();
12 if (!dfs(0, -1, visit, adj)) return false;
13
14 return visit.size() == n;
15 }
16
17 private boolean dfs(int i, int prev, Set<Integer> visit, List<List<Integer>> adj) {
18 if (visit.contains(i)) return false;
19
20 visit.add(i);
21 for (int j : adj.get(i)) {
22 if (j == prev) continue;
23 if (!dfs(j, i, visit, adj)) return false;
24 }
25 return true;
26 }
27}1class Solution {
2public:
3 bool validTree(int n, vector<vector<int>>& edges) {
4 if (n == 0) return true;
5 vector<vector<int>> adj(n);
6 for (auto& edge : edges) {
7 adj[edge[0]].push_back(edge[1]);
8 adj[edge[1]].push_back(edge[0]);
9 }
10
11 unordered_set<int> visit;
12 if (!dfs(0, -1, visit, adj)) return false;
13
14 return visit.size() == n;
15 }
16
17 bool dfs(int i, int prev, unordered_set<int>& visit, vector<vector<int>>& adj) {
18 if (visit.count(i)) return false;
19
20 visit.insert(i);
21 for (int j : adj[i]) {
22 if (j == prev) continue;
23 if (!dfs(j, i, visit, adj)) return false;
24 }
25 return true;
26 }
27};Time and space complexity
O(n + E)
Building the adjacency list touches each edge twice, and the DFS visits each node once and scans each adjacency entry once.
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.