class Node:
def __init__(self,left,value,right):
self.left = left
self.value = value
self.right = right
def min(self):
if self.left == None:
return self.value
else:
return self.left.min()
def size(self):
if self.left == None and self.right == None:
return 1
elif self.left == None and self.right != None:
return 1 + self.right.size()
elif self.left != None and self.right == None:
return 1 + self.left.size()
else:
return 1 + self.left.size() + self.right.size()
def insert(self,x):
if x < self.value:
if self.left == None:
self.left = Node(None,x,None)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right == None:
self.right = Node(None,x,None)
return True
else:
return self.right.insert(x)
else:
return False
def delete(self,x):
return self.delete_helper(x) != None
def delete_helper(self,x):
if self.value == x:
# yes! we can delete it
if self.left == None:
return self.right
elif self.right == None:
return self.left
else:
rmin = self.right.min()
self.value = rmin
self.right = self.right.delete_helper(rmin)
return self
elif x < self.value:
if self.left == None:
return None
else:
self.left = self.left.delete_helper(x)
return self
else:
if self.right == None:
return None
else:
self.right = self.right.delete_helper(x)
return self
def __str__(self):
if self.left != None:
if self.right != None:
return str(self.left) + "," + str(self.value) + "," + str(self.right)
else:
return str(self.left) + "," + str(self.value)
else:
if self.right != None:
return str(self.value) + "," + str(self.right)
else:
return str(self.value)
import sys
class BST:
def __init__(self):
self.root = None
def empty(self):
return self.root == None
def min(self):
if self.empty():
return -sys.maxsize
else:
return self.root.min()
def size(self):
if self.empty():
return 0
else:
self.root.size()
def insert(self,x):
if self.empty():
self.root = Node(None,x,None)
else:
self.root.insert(x)
def delete(self,x):
if self.empty():
return False
else:
return self.root.delete(x)
def __str__(self):
if self.empty():
return "{ }"
else:
return "{" + str(self.root) + "}"
t = BST()
t.insert(50)
t.insert(30)
t.insert(60)
t.insert(70)
t.insert(20)
print(t)
t.delete(700)
print(t)
{20,30,50,60,70} {20,30,50,60}
import sys
print(-sys.maxsize)
-9223372036854775807