-
Notifications
You must be signed in to change notification settings - Fork 1
/
traversal.py
38 lines (30 loc) · 1006 Bytes
/
traversal.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
from dataclasses import dataclass
from typing import Union, List
def breadth_first_search(tree):
frontier = []
def traverse(current):
while (node := frontier.pop()):
print(node.get('value', None))
traverse(node)
for node in node.get('children', []):
frontier.append(node)
frontier.append(tree)
traverse(tree)
def depth_first_search(tree):
frontier = []
def traverse(current):
while (node := frontier.pop()):
for node in node.get('children', []):
frontier.append(node)
traverse(node)
print(current.get('value', None))
traverse(tree)
tree = dict(value='0', children=[
dict(value='01', children=[dict(value='011'), dict(value='012'), dict(value='013')]),
dict(value='02', children=[dict(value='021'), dict(value='022'), dict(value='023')]),
])
print("BFS:")
breadth_first_search(tree)
# print('=' * 50)
# print("DFS:")
# depth_first_search(tree)