You are given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge connects a pair of nodes). Write a function to determine whether these edges form a valid tree.
You can assume there are no duplicate edges in the input. Since all edges are undirected, [a, b] is considered the same as [b, a].
Function Signature
def valid_tree(n: int, edges: list[list[int]]) -> bool:
Rules
-
A valid tree is connected and has no cycle. Every node must be part of it.
-
edges[i] = [a, b]
is an undirected edge between nodes
a
and
b
.
-
A single node with no edges (
n = 1
,
edges = []
) is a valid tree.
Constraints
-
1 <= n <= 125
-
0 <= len(edges) <= n * (n - 1) / 2
-
0 <= edges[i][0], edges[i][1] < n
, and each edge joins two different nodes.
-
No duplicate edges.
Examples
Input: n = 6, edges = [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]]
Output: True
Node 0 connects to 1, 2 and 3, and node 1 connects to 4 and 5. All six nodes are reachable and the five edges contain no cycle.
Input: n = 6, edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
Output: False
The edges [1, 2], [2, 3] and [1, 3] form a cycle, and node 5 has no edge at all. The edge count is exactly n - 1, but the graph is still not a tree.
Input: n = 1, edges = []
Output: True
One node with no edges is connected and has no cycle.