Graph Valid Tree
Medium Graphs
There are n nodes, numbered 0 to n - 1, and edges lists undirected links between them: an [a, b] pair joins nodes a and b, and a link works in both directions.
The edges make a valid tree when every node can be reached from every other by following edges, and there is no cycle: no route that leaves a node, uses each edge at most once, and comes back to that node.
Return true if the edges make a valid tree, and false otherwise.
Example 1
Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[4,5]]
Output: true
Example 2
Input: n = 4, edges = [[0,1],[1,2],[2,0],[2,3]]
Output: false
Every node can be reached, but nodes 0, 1 and 2 lead round in a loop.
Example 3
Input: n = 6, edges = [[0,1],[2,3],[4,5]]
Output: false
Constraints
1 ≤ n ≤ 10⁵0 ≤ edges.length ≤ 10⁵0 ≤ a, b < nanda ≠ bfor every edge[a, b]- no two edges join the same pair of nodes, in either order
Solve it here
Write it in Python, Java or C++, run it on your own cases, and submit against hidden tests.
More Graphs
- Number of IslandsAI round · Medium
- Rotting OrangesAI round · Medium
- Word LadderAI round · Hard
- Walls and GatesMedium
- Number of Connected Components in an Undirected GraphMedium