Skip to content

Commit 60f506b

Browse files
Solve : Graph Valid Tree
1 parent faeaa2b commit 60f506b

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution:
2+
def valid_tree(self, n, edges):
3+
if len(edges) != n - 1:
4+
return False
5+
parent = [i for i in range(n)]
6+
def find(x):
7+
while parent[x] != x:
8+
parent[x] = parent[parent[x]]
9+
x = parent[x]
10+
return x
11+
for u, v in edges:
12+
pu, pv = find(u), find(v)
13+
if pu == pv:
14+
return False
15+
parent[pu] = pv
16+
return True

0 commit comments

Comments
 (0)