-
Notifications
You must be signed in to change notification settings - Fork 65
/
dfs_traversals.py
100 lines (79 loc) · 2.55 KB
/
dfs_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
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
""" 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.
"""
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 preorder_traversal(node):
""" Pre Order Tree Traversal
* Visit the root node
* Visit all the nodes in the left subtree
* Visit all the nodes in the right subtree
"""
if node is None:
return
print(node.data, end=" ")
preorder_traversal(node.left)
preorder_traversal(node.right)
def inorder_traversal(node):
""" In Order Tree Traversal
* Visit all the nodes in the left subtree
* Visit the root node
* Visit all the nodes in the right subtree
"""
if node is None:
return
inorder_traversal(node.left)
print(node.data, end=" ")
inorder_traversal(node.right)
def postorder_traversal(node):
""" Post Order Tree Traversal
* Visit all the nodes in the left subtree
* Visit all the nodes in the right subtree
* Visit the root node
"""
if node is None:
return
postorder_traversal(node.left)
postorder_traversal(node.right)
print(node.data, end=" ")
def main():
""" operational function """
bst = BinarySearchTree()
for elem in [9, 5, 3, 10, 6, 1, 7, 4]:
bst.insert(elem)
preorder_traversal(bst.root)
print()
inorder_traversal(bst.root)
print()
postorder_traversal(bst.root)
print()
if __name__ == "__main__":
main()