Given n nodes labeled from 0 to n-1 and a list of undirected edges, determine if these edges form a valid tree.
A valid tree is a connected graph with exactly n-1 edges and no cycles. Think of it like a family tree or organizational chart - every node should be reachable from every other node, but there should be exactly one path between any two nodes.
Key Properties of a Tree:
- ๐ณ Connected: All nodes must be reachable
- ๐ซ Acyclic: No cycles allowed
- ๐ Minimal: Exactly n-1 edges (not more, not less)
Return true if the edges form a valid tree, false otherwise.
Input & Output
Visualization
Time & Space Complexity
We visit each node once and examine each edge once, where n is nodes and m is edges
Space for adjacency list (O(n + m)) plus visited set (O(n)) plus recursion stack (O(n) in worst case)
Constraints
- 1 โค n โค 2000
- 0 โค edges.length โค 5000
- edges[i].length == 2
- 0 โค ai, bi < n
- ai โ bi
- No duplicate edges in the input