Graph Valid Tree

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

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:

1. The graph is fully connected (there is exactly one connected component).

2. The graph has no cycles (it has exactly n - 1 edges).

Examples

Example 1:

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

Output: true

Explanation: The 5 nodes are all connected with 4 edges and no cycles, forming a valid tree.

Example 2:

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

Output: false

Explanation: The edge [1,3] creates a cycle between nodes 1, 2, and 3. A tree cannot have cycles.

Example 3:

Input: n = 4, edges = [[0,1],[2,3]]

Output: false

Explanation: Although there are no cycles, the graph has two 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 repeated edges.
Source: Union Find pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle