-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbfs_and_dfs_tree_traversal.py
108 lines (71 loc) · 2.12 KB
/
bfs_and_dfs_tree_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
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# Breadth First Tree Traversal
class Node:
'''
This class is used to create a node.
'''
def __init__(self, data=None):
self.left = None
self.val = data
self.right = None
class Tree:
'''
This class implements BFS and DFS traversal methods.
'''
def bfs_tree_traversal(self, root: Node):
'''
This method traverse a tree using Breadth First Search(BFS) algorithm.
'''
queue = []
queue.append(root)
while len(queue) > 0:
node = queue.pop(0)
print(node.val, end = '-')
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
def dfs_tree_traversal(self, root: Node):
'''
This method traverse a tree using Depth First Search(DFS) algorithm.
'''
stack = []
stack.append(root)
while len(stack) > 0:
node = stack.pop()
print(node.val, end = '-')
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
def main(root):
'''
This function creates tree object and calls its methods.
'''
# Raises AssertionError when a tree's root node is None.
assert root.val is not None, 'Tree Is Empty.'
tree = Tree()
print('BFS Tree Traversal: ', end = '')
tree.bfs_tree_traversal(root)
print('\nDFS Tree Traversal: ', end = '')
tree.dfs_tree_traversal(root)
# Driver code
if __name__ == '__main__':
'''
a
/ \
b c
/ \ /\
d e h i
/ \
f g
'''
root = Node('a')
root.left = Node('b')
root.right = Node('c')
root.left.left = Node('d')
root.left.right = Node('e')
root.left.left.left = Node('f')
root.left.right.right = Node('g')
root.right.left = Node('h')
root.right.right = Node('i')
main(root)