Pattern visualizer
Graph Valid Tree
A tree on n nodes always has exactly n - 1 edges, so that count is the first, cheap filter — but it is not proof by itself: a graph can hit that exact count by combining one small cycle with a disconnected leftover piece, which is exactly the graph below. The real check is union-find: start every node in its own set, and for each edge ask whether its two endpoints are already in the same set. If they are, the edge would close a loop, so the graph is disqualified on the spot; otherwise merge the two sets and continue. Reaching the last edge without ever finding a shared set is what actually proves both 'no cycles' and 'fully connected' at once. Animated on: n = 5, edges = [[0,1],[1,2],[2,0],[3,4]] — exactly n-1 = 4 edges, but is this a valid tree?.
Union-find: n-1 edges is necessary, a cycle check is what makes it sufficient
Undirected graph as given
5 nodes and 4 edges. A valid tree needs every node reachable and zero cycles — checking edge count first is cheap, but it only rules OUT some invalid graphs, so a cycle check still has to follow.
1FUNCTION validTree(n, edges):2 IF LENGTH(edges) != n - 13 RETURN false4 FOR i FROM 0 TO n - 15 parent[i] <- i6 FOR EACH (a, b) IN edges7 ra <- FIND(parent, a)8 rb <- FIND(parent, b)9 IF ra = rb10 RETURN false11 parent[ra] <- rb12 RETURN true
← / → step · space play · Home restart