Menu
CoddyTech

Graph Valid Tree

You get n nodes, numbered from 0 to n-1, and a list edges of undirected edges. Each pair [a, b] joins node a and node b.

Return true if the edges make all n nodes into one tree: every node can reach every other node, and there is no cycle. Return false otherwise.

Function

validTree(n: integer, edges: integer-2d-array) → boolean
ninteger
the number of nodes, numbered 0 to n-1
edgesinteger-2d-array
the undirected edges, each a pair [a, b]
Returnsboolean
true if the edges join all n nodes into one tree, false otherwise

Constraints

  • 2 ≤ n ≤ 104
  • 1 ≤ edges.length ≤ 5000
  • edges[i] = [a, b] with 0 ≤ a, b ≤ n-1 and a ≠ b
  • No edge appears twice, in either direction.

Examples

Input
n = 5edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
Output
true
Explanation
Node 0 links to nodes 1, 2 and 3, and node 4 hangs off node 1. Four edges join all five nodes with no loop, so this is a tree.
challenge icon

Follow-up

When the graph is not a tree, how many edges must you remove, and how many add, to make it one? Can you count both in one pass?

Reset code
def validTree(n, edges):
    # Write code here

Test #1

Test #2

Test #3

Arguments

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

Expected Output

true