Graphs Traversing a graph
451. Graph Valid Tree
You are given an undirected graph with n vertices, numbered from 0 to n - 1. Each pair [u, v] in
edges is an edge between vertices u and v, and it can be used in both directions.
Return true if the graph is a tree, and false otherwise. A tree is a graph that is connected and has
no cycle.
- Connected means that every vertex can be reached from every other vertex along edges.
- A cycle is a way to leave a vertex along one edge and come back to it along another, without using any edge twice.
Example 1
Input: n = 6
edges = [[0, 4],
[4, 2],
[1, 4],
[3, 1],
[5, 3]]
trueExplanation: Every vertex can be reached from vertex 0. The farthest is 5, along 0 → 4 → 1 → 3 → 5. No edge leads back to a vertex already passed, so there is no cycle.
Example 2
Input: n = 5, edges = [[0, 1], [1, 2], [2, 0], [3, 4]]
falseExplanation: Vertices 0, 1 and 2 form a cycle. Vertices 3 and 4 cannot be reached from the other three either.
Example 3
Input: n = 1, edges = []
trueExplanation: A single vertex is connected and has no cycle, so it is a tree.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 1050 ≤ edges.length ≤ 2 × 105edges[i].length == 20 ≤ ui, vi < nui ≠ vi- No edge appears twice:
[u, v]and[v, u]are the same edge.
Clarifying questions
What you would ask an interviewer before writing any code.