-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathBFS.py
More file actions
25 lines (25 loc) · 707 Bytes
/
BFS.py
File metadata and controls
25 lines (25 loc) · 707 Bytes
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
import random
class Node:
def __init__(self, value):
self.value = value
self.children = []
def add_child(self, child):
self.children.append(child)
def bfs(self):
queue = [self]
visited = set()
while queue:
node = queue.pop(0)
if node not in visited:
visited.add(node)
for child in node.children:
queue.append(child)
return visited
root = Node(random.randint(1, 100))
for i in range(10):
child = Node(random.randint(1, 100))
root.add_child(child)
# Perform a breadth-first search on the tree
visited = root.bfs()
for node in visited:
print(node.value)