-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathBinaryTree.py
224 lines (194 loc) · 5.22 KB
/
BinaryTree.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import sys
sys.path.append(".")
from Queue.queueLL import QueueLL
class _Node:
'''
Initialises node with the passed arguments, None if no arguments are passed.
'''
__slots__ = '_element', '_left', '_right'
def __init__(self, element, left=None, right=None):
self._element = element
self._left = left
self._right = right
class BinaryTree:
def __init__(self):
'''
Initialises Root node to None.
'''
self._root = None
self._count = 0
def __len__(self):
'''
Returns the length of Tree.
'''
return self._count
def createTree(self, node):
'''
Recursively adds node to the tree using Postorder traversing pattern.
That means, it will first ask to add all the left childs of root
and then right child of the most recently added node.
'''
# os.system('cls')
position = input(
f"Add node on the Left of {node._element} ? [y/n]: ")
if position == 'y':
nodeData = input("Enter data for node: ")
curr = _Node(nodeData)
node._left = curr
self.createTree(curr)
self._count += 1
# os.system('cls')
position = input(
f"Add node on the Right of {node._element} ? [y/n]: ")
if position == 'y':
nodeData = input("Enter data for node: ")
curr = _Node(nodeData)
node._right = curr
self.createTree(curr)
self._count += 1
def createRoot(self):
'''
Function to create Root node.
'''
rootData = input("Enter data for Root: ")
self._root = _Node(rootData)
self.createTree(self._root)
self._count += 1
def inorder(self, troot):
'''
Function for Inorder Traversal.
'''
if troot:
self.inorder(troot._left)
print(troot._element, end=" ")
self.inorder(troot._right)
def preorder(self, troot):
'''
Function for Preorder Traversal.
'''
if troot:
print(troot._element, end=" ")
self.preorder(troot._left)
self.preorder(troot._right)
def postorder(self, troot):
'''
Function for Postorder Traversal.
'''
if troot:
self.postorder(troot._left)
self.postorder(troot._right)
print(troot._element, end=" ")
def levelorder(self):
Q = QueueLL()
t = self._root
print(t._element, end=" ")
Q.enqueue(t)
while not Q.isempty():
t = Q.dequeue()
if t._left:
print(t._left._element, end=" ")
Q.enqueue(t._left)
if t._right:
print(t._right._element, end=" ")
Q.enqueue(t._right)
def height(self, troot):
'''
Utility function to calculate height of the tree.
'''
if troot:
x = self.height(troot._left)
y = self.height(troot._right)
if x > y:
return x + 1
else:
return y + 1
return 0
###############################################################################
def options():
'''
Prints Menu for operations
'''
options_list = ['Create Tree', 'Inorder', 'Preorder',
'Postorder', 'Level Order', 'Count',
'Height', 'Exit']
print("\nMENU")
for i, option in enumerate(options_list):
print(f'{i + 1}. {option}')
choice = int(input("Enter choice: "))
return choice
def switch_case(choice):
'''
Switch Case for operations
'''
# os.system('cls')
if choice == 1:
bt.createRoot()
elif choice == 2:
print("Inorder Traversal:")
bt.inorder(bt._root)
elif choice == 3:
print("Preorder Traversal:")
bt.preorder(bt._root)
elif choice == 4:
print("Postorder Traversal:")
bt.postorder(bt._root)
elif choice == 5:
print("Level Order Traversal:")
bt.levelorder()
elif choice == 6:
print("Number of Nodes: ",len(bt))
elif choice == 7:
print("Height: ", bt.height(bt._root) - 1)
elif choice == 8:
sys.exit()
###############################################################################
if __name__ == '__main__':
bt = BinaryTree()
while True:
choice = options()
switch_case(choice)
'''
MENU
1. Create Tree
2. Inorder
3. Preorder
4. Postorder
5. Exit
Enter choice: 1
Enter data for Root: 10
Add node on the Left of 10 ? [y/n]: y
Enter data for node: 20
Add node on the Left of 20 ? [y/n]: n
Add node on the Right of 20 ? [y/n]: n
Add node on the Right of 10 ? [y/n]: y
Enter data for node: 30
Add node on the Left of 30 ? [y/n]: n
Add node on the Right of 30 ? [y/n]: n
MENU
1. Create Tree
2. Inorder
3. Preorder
4. Postorder
5. Exit
Enter choice: 2
Inorder Traversal:
20 10 30
MENU
1. Create Tree
2. Inorder
3. Preorder
4. Postorder
5. Exit
Enter choice: 3
Preorder Traversal:
10 20 30
MENU
1. Create Tree
2. Inorder
3. Preorder
4. Postorder
5. Exit
Enter choice: 4
Postorder Traversal:
20 30 10
'''