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] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the graph.

Return true if the edges of the given graph make up a valid tree, and false otherwise.

A valid tree must satisfy two conditions:

  • All nodes are connected (exactly one connected component)
  • There are no cycles in the graph

For a tree with n nodes, there must be exactly n-1 edges.

Input & Output

Example 1 — Valid Tree
$ Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,4]]
Output: true
💡 Note: The graph forms a valid tree: 5 nodes with 4 edges, all connected, no cycles. Node 1 connects to nodes 0, 2, and 4, creating a tree structure.
Example 2 — Has Cycle
$ Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,4],[3,4]]
Output: false
💡 Note: The graph contains a cycle: 1→4→3→2→1. A valid tree cannot have cycles.
Example 3 — Disconnected
$ Input: n = 4, edges = [[0,1],[2,3]]
Output: false
💡 Note: The graph has 2 disconnected components: {0,1} and {2,3}. A tree must be fully connected.

Constraints

  • 1 ≤ n ≤ 2000
  • 0 ≤ edges.length ≤ 5000
  • edges[i].length == 2
  • 0 ≤ ai, bi < n
  • ai ≠ bi
  • There are no self-loops or repeated edges.

Visualization

Tap to expand
Graph Valid Tree ProblemInputn = 5edges = [[0,1],[1,2],[2,3],[1,4]]Validation✓ Edges: 4 = n-1✓ All connected✓ No cyclesOutputtrue01234🎯 Key Insight: Tree = Connected + Acyclic + Exactly n-1 edges
Understanding the Visualization
1
Input Graph
Given n nodes and edges list
2
Tree Properties
Check: exactly n-1 edges, connected, no cycles
3
Output
Return true if valid tree, false otherwise
Key Takeaway
🎯 Key Insight: A valid tree has exactly n-1 edges, is fully connected, and contains no cycles
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
125.0K Views
High Frequency
~25 min Avg. Time
1.6K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen