All problems
Graph Valid Tree Check
Problem
Decide whether an undirected graph with n nodes and the given edges is a valid tree.
A graph is a tree when it is connected and acyclic, which for n nodes is equivalent to having exactly n - 1 edges and no cycle. edges is a list of [u, v] pairs.
Hint
n - 1 edges plus no cycle implies connectivity.
Test cases
case 1
in: [5,[[0,1],[0,2],[0,3],[1,4]]]
expected: true
case 2
in: [5,[[0,1],[1,2],[2,3],[3,4],[4,0]]]
expected: false
case 3
in: [1,[]]
expected: true
case 4
in: [2,[]]
expected: false
case 5
in: [2,[[0,1]]]
expected: true
Starter codePython
def valid_tree(n, edges):
# Your code here
pass5 test cases · run your code against them in the editor