Skip to content

Commit 144ee0d

Browse files
committed
graph Valid Tree solution
1 parent a07710c commit 144ee0d

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

graph-valid-tree/doh6077.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+
# Valid Tree
4+
# 1. no loop
5+
# 2. no disconnected node
6+
# Use DFS and Hashset to track visited nodes
7+
if not n:
8+
return True
9+
10+
adj = {i:[] for i in range(n)}
11+
for n1, n2 in edges:
12+
adj[n1].append(n2)
13+
adj[n2].append(n1)
14+
visit = set()
15+
def dfs(i, prev):
16+
# Base case
17+
if i in visit:
18+
return False
19+
visit.add(i)
20+
# check neighbor nodes
21+
for j in adj[i]:
22+
if j == prev:
23+
continue
24+
if not dfs(j,i):
25+
return False
26+
return True
27+
28+
return dfs(0, -1) and n == len(visit)
29+
30+
31+
32+
33+

0 commit comments

Comments
 (0)