Skip to content

Instantly share code, notes, and snippets.

@rafiamafia
Last active June 17, 2018 19:28
Show Gist options
  • Save rafiamafia/be8864072cd4ec4d5ae278f1a65471ae to your computer and use it in GitHub Desktop.
Save rafiamafia/be8864072cd4ec4d5ae278f1a65471ae to your computer and use it in GitHub Desktop.
Python Binary Search Tree Implementation
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# To allow duplicates we can store extra information i.e count
# to optimize memory and make search, insert, delete easier
#self.count = 1
def insert(self, data):
if data == self.data:
return False
if data < self.data:
if self.left:
return self.left.insert(data)
else:
self.left = Node(data)
return True
else:
if self.right:
return self.right.insert(data)
else:
self.right = Node(data)
return True
def find(self, data):
if data == self.data:
return self
if data < self.data:
if self.left is not None:
self.left.find(data)
else:
if self.right is not None:
self.right.find(data)
return None
def delete(self, data):
if data < self.data:
if self.left:
self.left = self.left.delete(data)
else:
raise ValueError(data, ' does not exist.')
elif data > self.data:
if self.right:
self.right = self.right.delete(data)
else:
raise ValueError(data, ' does not exist.')
else:
if self.left is None:
return self.right
elif self.right is None:
return self.left
# self with 2 children, get the in order successor
temp = self.right.minValueNode()
self.data = temp.data
self.right = self.delete(self.right, temp.data)
return self
def minValueNode(self):
if self.left is None:
return self
else:
return self.left.minValueNode()
def height(self):
if self.left and self.right:
return 1 + max(self.left.height(), self.right.height())
elif self.left:
return 1 + self.left.height()
elif self.right:
return 1 + self.right.height()
else:
return 1
def inorder(self):
stack = []
node = self
inorder_str = ''
while stack or node:
if node:
stack.append(node)
node = node.left
else:
node = stack.pop()
inorder_str = inorder_str + ' ' + str(node.data)
print(node.data)
node = node.right
print(inorder_str.strip())
def preorder(self):
stack = []
stack.append(self)
preorder_str = ''
while stack:
node = stack.pop()
if node.right: stack.append(node.right)
if node.left: stack.append(node.left)
preorder_str = preorder_str + ' ' + str(node.data)
print(preorder_str.strip())
def postorder(self):
stack = []
node = self
postorder_str = ''
while stack or node:
if node:
stack.append(node)
node = node.left
else:
temp = stack[-1].right
if temp:
node = temp
else:
temp = stack.pop()
postorder_str = postorder_str + ' ' + str(temp.data)
while stack and temp == stack[-1].right:
temp = stack.pop()
postorder_str = postorder_str + ' ' + str(temp.data)
print(postorder_str.strip())
class BST:
def __init__(self):
self.root = None
def insert(self, data):
if self.root:
return self.root.insert(data)
else:
self.root = Node(data)
return True
def find(self, data):
if self.root is None:
return ValueError(data, ' does not exist, BST is empty.')
if self.root.data == data or self.root.find(data):
return True
return ValueError(data, ' does not exist.')
def delete(self, data):
if self.root is None:
return ValueError(data, ' does not exist, BST is empty.')
try:
self.root = self.root.delete(data)
except ValueError as err:
print(err)
finally:
self.printInOrder()
def minValue(self):
if self.root is None:
return Exception('BST is empty.')
return self.root.minValueNode().data
def height(self):
if self.root is None:
return 0
return self.root.height()
def printInOrder(self):
if self.root is None:
print('Tree is empty')
return
print('Printing tree in order')
self.root.inorder()
def printPreOrder(self):
if self.root is None:
print('Tree is empty')
return
print('Printing tree preorder')
self.root.preorder()
def printPostOrder(self):
if self.root is None:
print('Tree is empty')
return
print('Printing tree postorder')
self.root.postorder()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment