Skip to content

Commit 02d6d3b

Browse files
author
wuduhren
committed
update
1 parent 5a67c5f commit 02d6d3b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

problems/python3/graph-valid-tree.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution:
2+
def validTree(self, N: int, edges: List[List[int]]) -> bool:
3+
def union(n1, n2) -> bool:
4+
p1 = find(n1)
5+
p2 = find(n2)
6+
7+
if p1==p2:
8+
return False
9+
elif p1<p2:
10+
parents[p2] = p1
11+
else:
12+
parents[p1] = p2
13+
14+
return True
15+
16+
17+
def find(n) -> int:
18+
p = parents[n]
19+
while p!=parents[p]: p = find(p)
20+
parents[n] = p
21+
return p
22+
23+
parents = [n for n in range(N)]
24+
25+
for n1, n2 in edges:
26+
if not union(n1, n2): return False
27+
28+
#check if all node trace back to the same root
29+
root = find(0)
30+
for n in range(1, N):
31+
if root!=find(n): return False
32+
33+
return True

0 commit comments

Comments
 (0)