-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathBST_operations.py
51 lines (45 loc) · 1.21 KB
/
BST_operations.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
class Node:
def __init__(self, val_pos, val):
self.val_pos = val_pos
self.val = val
self.left = None
self.right = None
class BST:
def __init__(self):
self.head = None
def addElement(self, val):
if(self.head == None):
self.head = Node(1, val)
return(1)
else:
a = self.head
while(a != None):
val_pos = a.val_pos
if(a.val < val):
a = a.right
exp = "2*val_pos+1"
else:
a = a.left
exp = "2*val_pos"
x = eval(exp)
a = Node(x, val)
return(x)
def deleteElement(self, val):
a = self.head
while(a != None):
if(a.val < val):
a = a.right
elif(a.val > val):
a = a.left
else:
x = a.val_pos
a = None
return(x)
Q = int(input())
BinarySearchTree = BST()
for i in range(Q):
a = input().split(" ")
if(a[0] == "i"):
print(BinarySearchTree.addElement(int(a[1])))
else:
print(BinarySearchTree.deleteElement(int(a[1])))