forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChaedie.py
More file actions
39 lines (31 loc) · 845 Bytes
/
Chaedie.py
File metadata and controls
39 lines (31 loc) · 845 Bytes
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
30
31
32
33
34
35
36
37
38
39
"""
Conditions of Valid Tree
1) no Loop
2) all nodes has to be connected
Time: O(node + edge)
Space: O(node + edge)
"""
class Solution:
def validTree(self, n: int, edges: List[List[int]]) -> bool:
if not n:
return True
if len(edges) != n - 1:
return False
# Make Graph
graph = {i: [] for i in range(n)}
for n1, n2 in edges:
graph[n1].append(n2)
graph[n2].append(n1)
# loop check
visit = set()
def dfs(i, prev):
if i in visit:
return False
visit.add(i)
for j in graph[i]:
if j == prev:
continue
if not dfs(j, i):
return False
return True
return dfs(0, None) and n == len(visit)