Graph Valid Tree Problem
Description
LeetCode Problem 261.
You have a graph of n nodes labeled from 0 to n - 1. You are given an integer n and a list of edges where edges[i] = [a_i, b_i] indicates that there is an undirected edge between nodes a_i and b_i in the graph.
Return true if the edges of the given graph make up a valid tree, and false otherwise.
Example 1:

Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
Output: true
Example 2:

Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
Output: false
Constraints:
1 <= n <= 20000 <= edges.length <= 5000edges[i].length == 20 <= a_i, b_i < na_i != b_i- There are no self-loops or repeated edges.
Solution
Approach: Edge Count + Union-Find
A graph on n nodes is a tree when it is connected and has no cycle. Any two of these three facts imply the third: connected, no cycle, exactly n - 1 edges. So we check two of them:
- Exactly
n - 1edges. If not, returnfalseright away. - No cycle. Use union-find: start with every node in its own set, and for each edge
[a, b]find the roots ofaandb. If they are the same,aandbare already connected, and this edge closes a cycle. Otherwise merge the two sets.
With n - 1 edges and no cycle, every edge merges two different components, so n components become 1: the graph is connected.
Do not skip the edge count. n = 4 with edges [[0,1],[2,3]] has no cycle but is two separate pieces, and n = 4 with [[0,1],[1,2],[2,0]] has the right count but a cycle (and node 3 is cut off). We use path halving in find to keep the trees flat.
Complexity: O(n · α(n)) time, almost linear (α is the inverse Ackermann function), and O(n) space for the parent array.
class Solution:
def validTree(self, n: int, edges: List[List[int]]) -> bool:
if len(edges) != n - 1: # a tree on n nodes has exactly n - 1 edges
return False
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
for a, b in edges:
ra, rb = find(a), find(b)
if ra == rb: # a and b are already connected: this edge closes a cycle
return False
parent[ra] = rb
# n - 1 edges and no cycle means the graph is connected.
return True