Depth-First Search
Medium

Graph Valid Tree

Determine if a set of edges forms a valid tree.
Examples
Input:n = 5, edges = [[0,1], [0,2], [0,3], [1,4]]
Output:true
Explain:

No cycles, fully connected.

Input:n = 5, edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Output:false
Explain:

Cycle exists: 1-2-3-1.

Problem Understanding

A Tree is a special type of Graph that satisfies two conditions:

  1. Fully Connected: You can reach any node from any other node.
  2. Acyclic: It contains no cycles.

Alternatively: A graph with N nodes is a tree if it is fully connected and has exactly N - 1 edges.

Algorithm Strategy (DFS)

We can use DFS to check for cycles and connectivity.

  1. Build Graph: Create adjacency list.
  2. DFS from Node 0: Keep track of visited set to detect cycles.
    • Since the graph is undirected, A-B means B is a neighbor of A. We must not count the immediate parent as a cycle.
    • Pass parent to the DFS call: dfs(node, parent).
    • If neighbor != parent and neighbor is visited -> Cycle Detected! Return false.
  3. Check Connectivity: After DFS, visited.size() must equal n. If not, the graph is disconnected.
Visualization
Step 1 / 8
0011 (Hub)223344

Problem: Is this a Valid Tree? (Connected, No Cycles). Start DFS(0).

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep