cheetcode

91. Graph Valid TreeMedium

Determine whether an undirected graph is connected and acyclic.

Given n nodes labeled 0 to n - 1 and a list of undirected edges, return true if the graph forms a valid tree.

Model the relationships explicitly, then choose BFS, DFS, or union find based on the question. Track visited state so cycles do not create repeated work.

Examples

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

Constraints

  • 1 <= n <= 2000
  • 0 <= edges.length <= 5000