class BST:
def __init__(self):
self._left = None ## is the left subtree
self._value = None
self._right = None ## is the right subtree
def empty(self):
return self._value == None
def minBST(self):
if self.empty(): #BASE Case if not found
return None
elif self._left == None:
return self._value
else:
return self._left.minBST()
def maxBST(self):
if self.empty(): #BASE Case if not found
return None
elif self._right == None:
return self._value
else:
return self._right.maxBST()
def member(self,x):
if self.empty(): #BASE Case if not found
return False
elif x < self._value:
return self._left.member(x)
elif x > self._value:
return self._right.member(x)
else: # BASE Case if found
return True
def height(self):
if self.empty():
return 0
else:
return 1 + max(self._left.height(),self._right.height())
def size(self):
if self.empty(): #BASE Case
return 0
else:
return 1 + self._left.size() + self._right.size()
def insert(self,x): # return a boolean; True if successful and False otherwise
if self.empty(): # BASE CASE
self._value = x
self._left = BST() ## MOST CRITICAL PART OF CODE; should not be None; This is where
## a future insert will happen
self._right = BST() ## MOST CRITICAL PART OF CODE; should not be None
elif x < self._value:
return self._left.insert(x)
elif x > self._value:
return self._right.insert(x)
else: # item found BASE CASE
return False
def delete(self,x):
return self.delete_helper(x) != None
def delete_helper(self,x):
if self.empty():
return None
elif x == self._value:
if self._right.empty():
return self._left
elif self._left.empty():
return self._right
else:
rmin = self._right.min()
self._value = rmin
self._right = self._right.delete_helper(rmin)
return self
elif x < self._value:
t = self._left.delete_helper(x)
if t == None:
return None
else:
self._left = t
return self
else:
t = self._right.delete_helper(x)
if t == None:
return None
else:
self._right = t
return self
def __str__(self):
return "{ " + self.str_helper().strip(', ') + " }"
def str_helper(self):
if self.empty():
return ""
else:
return self._left.str_helper()+str(self._value)+", "+self._right.str_helper()
def main():
#t1 = BST(BST(BST(),10,BST()), 20, BST(BST(),30,BST()))
#t2 = BST(BST(BST(BST(),10,BST()),20,BST(BST(),30,BST())), \
# 40, \
# BST(BST(BST(),50,BST()),600,BST(BST(),70,BST())))
nums = [47,34,97,88,41,20,16,105,100,83,99,97]
t3 = BST()
for x in nums:
t3.insert(x)
t4 = BST()
for x in nums[::-1]:
t4.insert(x)
print("************************")
print("BST t3")
print(t3)
print("************************")
print("BST t4")
print(t4)
print("************************")
main()
[1,2,3][::-1]