Skip to content

Commit 3fd7e0b

Browse files
committed
solve: graph valid tree
1 parent b5601c8 commit 3fd7e0b

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

graph-valid-tree/evan.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def validTree(self, n: int, edges: List[List[int]]) -> bool:
6+
# If the number of edges is not equal to n-1, it can't be a tree
7+
if len(edges) != n - 1:
8+
return False
9+
10+
# Initialize node_list array where each node is its own parent
11+
node_list = list(range(n))
12+
13+
# Find root function with path compression
14+
def find_root(node):
15+
if node_list[node] != node:
16+
node_list[node] = find_root(node_list[node])
17+
18+
return node_list[node]
19+
20+
def union_and_check_cycle(node1, node2):
21+
root1 = find_root(node1)
22+
root2 = find_root(node2)
23+
24+
if root1 != root2:
25+
node_list[root2] = root1
26+
return True
27+
else:
28+
return False
29+
30+
for node1, node2 in edges:
31+
if not union_and_check_cycle(node1, node2):
32+
return False
33+
34+
return True
35+
36+
37+
# Example usage:
38+
solution = Solution()
39+
print(solution.validTree(5, [[0, 1], [0, 2], [0, 3], [1, 4]])) # Output: True
40+
print(solution.validTree(5, [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]])) # Output: False

0 commit comments

Comments
 (0)