forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph-valid-tree.py
71 lines (64 loc) · 2.17 KB
/
graph-valid-tree.py
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
# Time: O(|V| + |E|)
# Space: O(|V| + |E|)
# BFS solution. Same complexity but faster version.
class Solution:
# @param {integer} n
# @param {integer[][]} edges
# @return {boolean}
def validTree(self, n, edges):
if len(edges) != n - 1: # Check number of edges.
return False
elif n == 1:
return True
# A structure to track each node's [visited_from, neighbors]
visited_from = [-1] * n
neighbors = collections.defaultdict(list)
for u, v in edges:
neighbors[u].append(v)
neighbors[v].append(u)
if len(neighbors) != n: # Check number of nodes.
return False
# BFS to check whether the graph is valid tree.
visited = {}
q = collections.deque([0])
while q:
i = q.popleft()
visited[i] = True
for node in neighbors[i]:
if node != visited_from[i]:
if node in visited:
return False
else:
visited[node] = True
visited_from[node] = i
q.append(node)
return len(visited) == n
# Time: O(|V| + |E|)
# Space: O(|V| + |E|)
# BFS solution.
class Solution2:
# @param {integer} n
# @param {integer[][]} edges
# @return {boolean}
def validTree(self, n, edges):
# A structure to track each node's [visited_from, neighbors]
visited_from = [-1] * n
neighbors = collections.defaultdict(list)
for u, v in edges:
neighbors[u].append(v)
neighbors[v].append(u)
# BFS to check whether the graph is valid tree.
visited = {}
q = collections.deque([0])
while q:
i = q.popleft()
visited[i] = True
for node in neighbors[i]:
if node != visited_from[i]:
if node in visited:
return False
else:
visited[node] = True
visited_from[node] = i
q.append(node)
return len(visited) == n