Description
Given n nodes labeled from 0 to n-1 and a list of undirected edges, check if these edges form a valid tree (connected and no cycles).
Examples
Input:
n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]Output:
trueExplanation:
Forms a valid tree with 5 nodes and 4 edges.
Input:
n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]Output:
falseExplanation:
No valid path or connection exists for the given input.
Input:
n = 4, edges = [[0,1],[2,3]]Output:
falseExplanation:
The graph has 4 nodes but only 2 edges connecting nodes 0-1 and 2-3, forming two separate components. A valid tree must be connected, so this returns false.
Constraints
- •
1 ≤ n ≤ 2000 - •
0 ≤ edges.length ≤ 5000