forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph-valid-tree.py
More file actions
33 lines (25 loc) · 866 Bytes
/
graph-valid-tree.py
File metadata and controls
33 lines (25 loc) · 866 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
class Solution:
def validTree(self, N: int, edges: List[List[int]]) -> bool:
def union(n1, n2) -> bool:
p1 = find(n1)
p2 = find(n2)
if p1==p2:
return False
elif p1<p2:
parents[p2] = p1
else:
parents[p1] = p2
return True
def find(n) -> int:
p = parents[n]
while p!=parents[p]: p = find(p)
parents[n] = p
return p
parents = [n for n in range(N)]
for n1, n2 in edges:
if not union(n1, n2): return False
#check if all node trace back to the same root
root = find(0)
for n in range(1, N):
if root!=find(n): return False
return True