-
Notifications
You must be signed in to change notification settings - Fork 66
/
bfs_traversals.py
75 lines (57 loc) · 1.97 KB
/
bfs_traversals.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
""" Binary Search Tree Traversals
DFS (Depth-first search) is technique used for traversing tree or graph.
Here backtracking is used for traversal. In this traversal first the
deepest node is visited and then backtracks to it’s parent node if no
sibling of that node exist.
"""
from collections import deque
class Node:
""" Node contains actual data and address to left and right node """
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinarySearchTree:
""" Binary Search Tree Implementation """
def __init__(self):
self.root = None
def insert(self, data):
""" inserts new integer data into the tree at the position, so that
the binary search tree property is maintained.
"""
def _insert(root, data):
""" recursive internal method which works on node level """
if root is None:
root = Node(data)
elif data <= root.data:
root.left = _insert(root.left, data)
else:
root.right = _insert(root.right, data)
return root
if self.root is None:
self.root = Node(data)
else:
self.root = _insert(self.root, data)
def level_order_traversal(self):
""" Breadth First Traversal (Level Order Traversal) """
if self.root is None:
return
queue = deque()
queue.append(self.root)
while queue:
node = queue[0]
print(node.data, end=" ")
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
queue.popleft()
def main():
""" operational function """
bst = BinarySearchTree()
for elem in [9, 5, 3, 10, 6, 1, 7, 4]:
bst.insert(elem)
bst.level_order_traversal()
print()
if __name__ == "__main__":
main()