Leetcode 261. Graph Valid Tree
题目
Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
Example 1:
Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
Output: true
Example 2:
Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Output: false
解法1:DFS
edges构成边需符合两个条件:
- 所有边构成连通图
- 所有边不成环
这边是无向图的环检测,有向图的换检测参见207. Course Schedule
是否构成连通图的判断:
构建visited数组,数组长度与节点数相同,构成连通图的必要条件是这个数组中每个元素都被访问
环检测:
访问到visited中已经有的元素即为成环。但是由于这边在构建dict时是双向的,所以还需要判断当前节点的parent节点。
class Solution:
def validTree(self, n: int, edges: List[List[int]]) -> bool:
if