Example 1
- Input
- n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
- Output
- true
Four edges link all five nodes with no cycle, which is exactly a tree.
Given a node count and undirected edges, decide whether they form exactly one tree. A valid tree connects every node with no cycles.
You are given n nodes labeled 0 to n - 1 and an undirected edges list.
Return true when the edges form a valid tree: every node reachable from every other node, with no cycles. Any connected graph with exactly n - 1 edges qualifies.
Four edges link all five nodes with no cycle, which is exactly a tree.
Edges 1-2, 2-3 and 1-3 close a cycle, so the graph cannot be a tree.
The single node is connected to itself by the empty path. It needs no edges and contains no cycle.
The edge count is n - 1, but nodes 0, 1 and 2 form a cycle and node 3 is isolated. Counting edges alone would accept this invalid graph.
Both components are individually acyclic, but there is no path from 0 to 2. Two edges are fewer than the three needed to connect all four nodes.
A tree uses one edge to attach each new node to the nodes already connected, so it needs exactly n - 1 edges and cannot join two nodes already linked by a path. In Example 1, 0 attaches 1, 2 and 3, then 1 attaches 4. The edge count alone is insufficient: a triangle plus an isolated node has three edges on four nodes but is not connected. DFS checks reachability and cycles directly; union-find remembers connected groups without constructing adjacency lists.
Reveal DFS Connectivity: intuition, complexity, and code
n nodes always has exactly n - 1 edges, so any other count answers false at once.n - 1 successful merges prove connection.Tree validation splits into counting edges and testing structure; union-find folds both into one pass by treating a redundant union as a cycle.