-
Notifications
You must be signed in to change notification settings - Fork 51
/
Binary Trave__.py
84 lines (78 loc) · 2.65 KB
/
Binary Trave__.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
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BTree:
def __init__(self):
self.root = None
self.temproot = None
def insert(self, newdata):
if self.root == None:
self.root = newdata
elif self.temproot:
if newdata.data < self.temproot.data:
if self.temproot.left == None:
self.temproot.left = newdata
self.temproot=None
else:
self.temproot = self.temproot.left
self.insert(newdata)
elif newdata.data > self.temproot.data:
if self.temproot.right == None:
self.temproot.right = newdata
self.temproot=None
else:
self.temproot = self.temproot.right
self.insert(newdata)
elif self.root:
if newdata.data < self.root.data:
if self.root.left == None:
self.root.left = newdata
elif self.root.left:
self.temproot = self.root.left
self.insert(newdata)
elif newdata.data > self.root.data:
if self.root.right == None:
self.root.right = newdata
elif self.root.right:
self.temproot = self.root.right
self.insert(newdata)
def preorder(self, temp):
if temp != None:
print(temp.data,",",end="")
self.preorder(temp.left)
self.preorder(temp.right)
def inorder(self, temp):
if temp != None:
self.inorder(temp.left)
print(temp.data,",",end="")
self.inorder(temp.right)
def postorder(self, temp):
if temp != None:
self.postorder(temp.left)
self.postorder(temp.right)
print(temp.data,",",end="")
BinaryTree = BTree()
while True:
print("1.Insert")
print("2.Preorder")
print("3.Inorder")
print("4.Postorder")
print("5.Exit")
choice = int(input("Enter the Choice : "))
if choice == 1:
element = int(input("Enter the Data : "))
data = Node(element)
BinaryTree.insert(data)
elif choice == 2:
BinaryTree.preorder(BinaryTree.root)
print("")
elif choice == 3:
BinaryTree.inorder(BinaryTree.root)
print("")
elif choice == 4:
BinaryTree.postorder(BinaryTree.root)
print("")
elif choice == 5:
break