oneby7

Graphs Traversing a graph

451. Graph Valid Tree

Medium

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

012345

Input: n = 6 edges = [[0, 4], [4, 2], [1, 4], [3, 1], [5, 3]]

Output: true

Explanation: 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

01234

Input: n = 5, edges = [[0, 1], [1, 2], [2, 0], [3, 4]]

Output: false

Explanation: Vertices 0, 1 and 2 form a cycle. Vertices 3 and 4 cannot be reached from the other three either.

Example 3

0

Input: n = 1, edges = []

Output: true

Explanation: 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.

n = 4, edges = [[0, 1], [2, 3]]

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ edges.length ≤ 2 × 105
  • edges[i].length == 2
  • 0 ≤ ui, vi < n
  • ui ≠ 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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.