Talentd
FleetCode

261. Graph Valid Tree

Medium49.9% acceptance9 companiesPremium elsewhere, free here

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

Example 2:

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

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.

Hints open one at a time

Hint 1
Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree?
Hint 2
According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
14:11
Still stuck?Read 2 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
5
[[0,1],[0,2],[0,3],[1,4]]
Input
5
[[0,1],[1,2],[2,3],[1,3],[1,4]]
Your code is saved on this device.Solution