forked from yingl/LintCodeInPython
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph_valid_tree.py
More file actions
Latest commit
29 lines (27 loc) · 1.07 KB
/
Copy pathgraph_valid_tree.py
File metadata and controls
29 lines (27 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# -*- coding: utf-8 -*-
classSolution:
# @param {int} n an integer
# @param {int[][]} edges a list of undirected edges
# @return {boolean} true if it's a valid tree, or false
defvalidTree(self, n, edges):
# Write your code here
# 如果是树,n个点有n - 1条边,遍历后包含所有点。
iflen(edges) != (n-1):
returnFalse
# 重新构造无向树,[m, n] => t[m][n] = t[n][m] = True。
tree= [[False] *nforiinxrange(n)]
visited= [False] *n
foredgeinedges:
tree[edge[0]][edge[1]] =True
tree[edge[1]][edge[0]] =True
# 从节点0开始深度遍历,这里顺便解决了输入为"1, []"的情况。
self.dfs(tree, visited, 0)
foriinxrange(n):
ifnotvisited[i]:
returnFalse
returnTrue
defdfs(self, tree, visited, node):
visited[node] =True
foriinxrange(len(tree[node])):
iftree[node][i] and (notvisited[i]):
self.dfs(tree, visited, i)