class Node:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
class binarySearchTree:
def __init__(self):
self.root = None
def remove(self, value):
if self.root.value == value:
temp = self.root.right
self.root = temp.left
self.root.right = temp
else:
curr = self.root
while curr != None and curr.value != value:
if value > curr.value and curr.right != None:
temp = curr
curr = curr.right
elif value < curr.value and curr.left != None:
temp = curr
curr = curr.left
else:
break
if curr.right == None and curr.left == None:
if(temp.value > curr.value):
temp.left = None
else:
temp.right = None
curr == None
print("removed")
elif curr.right != None and curr.left == None:
if(temp.value > curr.value):
temp.left = curr.right
else:
temp.right = curr.right
print("removed")
elif curr.right == None and curr.left != None:
if(temp.value > curr.value):
temp.left = curr.left
else:
temp.right = curr.left
print("removed")
else:
if(temp.value > curr.value):
temp.left = curr.right
else:
temp.right = curr.right
print("removed")
def insert(self,value):
node = Node(value)
if self.root == None:
self.root = node
else:
curr = self.root
while curr != None:
if node.value > curr.value and curr.right != None:
curr = curr.right
elif node.value < curr.value and curr.left != None:
curr = curr.left
else:
break
if node.value > curr.value:
curr.right = node
if node.value < curr.value:
curr.left = node
if __name__ == '__main__':
bst = binarySearchTree()
bst.insert(9)
bst.insert(4)
bst.insert(6)
bst.insert(20)
bst.insert(99)
bst.insert(15)
bst.insert(1)
bst.remove(4)
bst.remove(20)
bst.remove(9)
print(bst.root.value)
print(bst.root.left.value)
print(bst.root.right.value)