Graph Valid Tree
Master this topic with zero to advance depth.
Graph Valid Tree
You have a graph of n nodes labeled from 0 to n - 1. You are given an array 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.
Visual Representation
n=5, edges=[[0,1],[0,2],[0,3],[1,4]]
0
/|\n 1 2 3
|
4
Valid Tree! Result: trueExamples
All nodes are connected and there are no cycles.
Level I: Brute Force (DFS / BFS)
Intuition
A graph is a tree if it is connected and has no cycles. We can perform a traversal from any node and check:
- Did we visit all nodes?
- Did we encounter any already-visited nodes during traversal (cycle)?
Thought Process
- Build adjacency list.
- Start DFS from node 0.
- Keep track of
visitednodes. For each neighbor, make sure it's not the immediate parent (to handle undirected edges). - If a neighbor is already in
visited, returnFalse(cycle). - After DFS, check if
visited.size() == n.
Pattern: Cycle Detection in Undirected Graph
Detailed Dry Run
n=3, edges=[[0,1],[1,2],[2,0]]
- DFS(0): mark 0 visited, neighbor 1.
- DFS(1): mark 1 visited, neighbor 0 (skip), neighbor 2.
- DFS(2): mark 2 visited, neighbor 1 (skip), neighbor 0 (ALREADY VISITED!) -> Cycle found, return False.
Level III: Optimal (Union-Find)
Intuition
This is the most efficient way to check for both conditions. As we add edges, if two nodes already have the same root, adding an edge between them creates a cycle. Connectivity is guaranteed if we process exactly edges without cycles.
Thought Process
- Fundamental Tree Property: A valid tree with nodes MUST have exactly edges. If
len(edges) != n - 1, returnFalse. - Use Union-Find (DSU) with Path Compression.
- For each edge
(u, v):- Find roots of
uandv. - If roots are the same, return
False(cycle detected). - Otherwise, union them.
- Find roots of
- If all edges processed, return
True.
Pattern: Disjoint Set Union (DSU)
Detailed Dry Run
n=4, edges=[[0,1],[1,2],[2,3]]
- Edge (0,1): Union(0,1). Roots: 0,1. OK.
- Edge (1,2): Union(1,2). Roots: 0,2. OK.
- Edge (2,3): Union(2,3). Roots: 0,3. OK. All connected, no cycles. True.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.