hardGraphsPure DSA~30 min
Is the Undirected Network Exactly a Tree
Validate that a set of bidirectional links over n nodes forms a tree: fully connected with no cycles.
Problem
Given n nodes labelled 0..n-1 and a list edges of undirected connections, return true if the edges form a valid tree (connected and acyclic), and false otherwise.
Input
An integer n and a list edges of undirected [a, b] pairs.
Output
A boolean: whether the graph is a tree.
Constraints
- 1 <= n <= 2000
- 0 <= edges.length <= 5000
- No self-loops or duplicate edges.
Examples
Example 1
Input
n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
Output
true
Four edges connect five nodes with no cycle — a tree.
Example 2
Input
n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
Output
false
Edges 1-2-3-1 form a cycle.