-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path261. Graph-Valid-Tree
73 lines (63 loc) · 1.87 KB
/
261. Graph-Valid-Tree
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from typing import (
List,
)
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
root_x = self.find(x)
root_y = self.find(y)
if root_x != root_y:
if self.rank[root_x] > self.rank[root_y]:
self.parent[root_y] = root_x
elif self.rank[root_y] > self.rank[root_x]:
self.parent[root_x] = root_y
else:
self.parent[root_y] = root_x
self.rank[root_x] += 1
return False
return True
class Solution:
"""
@param n: An integer
@param edges: a list of undirected edges
@return: true if it's a valid tree, or false
"""
def valid_tree(self, n: int, edges: List[List[int]]) -> bool:
# write your code here
uf = UnionFind(n)
if n - 1 != len(edges):
return False;
for u, v in edges:
if uf.union(u,v):
return False;
return True
from typing import (
List,
)
class Solution:
"""
@param n: An integer
@param edges: a list of undirected edges
@return: true if it's a valid tree, or false
"""
def valid_tree(self, n: int, edges: List[List[int]]) -> bool:
# write your code here
def find_root(node):
if parent[node] != node:
parent[node] = find_root(parent[node])
return parent[node]
parent = list(range(n))
for node1, node2 in edges:
root1 = find_root(node1)
root2 = find_root(node2)
if root1 == root2:
return False;
parent[root1] = root2;
n -= 1
return n == 1