90. Graph Valid Tree
You have a graph of n nodes labeled from 0 to n - 1.
You are given an integer n and a list of edges where edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the graph.
Return true if the edges of the given graph make up a valid tree, and false otherwise.
Example 1:
Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
Output: true
Explanation:
The graph consists of 5 nodes labeled from 0 to 4 and has 4 edges. A valid tree must have exactly n-1 edges, which in this case is 4, so the count is correct.
Additionally, there are no cycles because every new edge connects a previously disconnected node.
The graph is also fully connected, meaning all nodes can be reached from any other node.
Since all conditions of a tree are satisfied, the given graph forms a valid tree.
Example 2:
Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
Output: false
Explanation:
The graph consists of 5 nodes and 5 edges. A valid tree must have exactly n-1 edges, but here there are 5 edges instead of 4, which is already a problem.
Additionally, the edge [1,3] forms a cycle because there is already a path from 1 to 3 through 1-2-3.
Even though the graph is connected, the presence of a cycle means it does not satisfy the conditions of a tree.
Therefore, the given graph is not a valid tree.
Now Your Turn!
Pick the correct output for the given inputInput : n = 3 , edges = [[0,1],[1,2]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= n <= 2000
- 0 <= edges.length <= 5000
- edges[i].length == 2
- 0 <= ai, bi < n
- ai != bi
- There are no self-loops or repeated edges.