Graph Valid Tree

Medium Graphs

There are n nodes, numbered 0 to n - 1, and edges lists undirected links between them: an [a, b] pair joins nodes a and b, and a link works in both directions.

The edges make a valid tree when every node can be reached from every other by following edges, and there is no cycle: no route that leaves a node, uses each edge at most once, and comes back to that node.

Return true if the edges make a valid tree, and false otherwise.

Example 1

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

Example 2

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

Every node can be reached, but nodes 0, 1 and 2 lead round in a loop.

Example 3

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

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ edges.length ≤ 10⁵
  • 0 ≤ a, b < n and a ≠ b for every edge [a, b]
  • no two edges join the same pair of nodes, in either order

More Graphs

All Graphs problems