Graph Valid Tree
Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #261
Given n nodes labeled 0..n-1 and a list of undirected edges, return true if the edges form a valid tree: connected and with no cycles.
Examples
text
n = 5, edges = [[0,1],[0,2],[0,3],[1,4]] → true
n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]] → false (cycle 1–2–3)Hints
- How many edges does a tree with n nodes have?
- If the edge count is right, then connectivity alone decides it. Or union-find: any edge joining two nodes already in the same set makes a cycle.
Approach
Theorem: a graph with n nodes is a tree ⟺ it has n − 1 edges and is connected ⟺ it has n − 1 edges and is acyclic.
- If
len(edges) != n − 1, return false. - Union-Find over the edges. If
find(a) == find(b)for some edge, there's a cycle, so return false. Otherwise it's a tree. (With exactly n−1 edges and no cycle, the graph must be connected.)
A BFS from 0 that counts the nodes reached also works after the edge-count check.
Complexity
Time: O(n · α(n)). Space: O(n).
Python solution
def validTree(n, edges):
if len(edges) != n - 1:
return False
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for a, b in edges:
ra, rb = find(a), find(b)
if ra == rb:
return False
parent[ra] = rb
return TrueJavaScript solution
function validTree(n, edges) {
if (edges.length !== n - 1) return false;
const parent = [...Array(n).keys()];
const find = (x) => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; };
for (const [a, b] of edges) {
const ra = find(a), rb = find(b);
if (ra === rb) return false;
parent[ra] = rb;
}
return true;
}