-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path261_Graph_Valid_Tree.py
More file actions
36 lines (26 loc) · 887 Bytes
/
Copy path261_Graph_Valid_Tree.py
File metadata and controls
36 lines (26 loc) · 887 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
class Solution:
def validTree(self, n: int, edges: List[List[int]]) -> bool:
self.adjList = {}
self.visit = set()
for i in range(n):
self.adjList[i] = []
for edge in edges:
self.adjList[edge[0]].append(edge[1])
self.adjList[edge[1]].append(edge[0])
if self.checkForCycle(0, -1):
return False
# did we visit all the nodes
for i in range(n):
if i not in self.visit:
return False
return True
def checkForCycle(self, node: int, parent) -> bool:
if node in self.visit:
return True
self.visit.add(node)
for adjecent in self.adjList[node]:
if parent == adjecent:
continue
if self.checkForCycle(adjecent, node):
return True
return False