Skip to content

Instantly share code, notes, and snippets.

@Ian-Gabaraev
Created April 28, 2020 14:10
Show Gist options
  • Save Ian-Gabaraev/fae31eeb845119978278b54f02c3e2b5 to your computer and use it in GitHub Desktop.
Save Ian-Gabaraev/fae31eeb845119978278b54f02c3e2b5 to your computer and use it in GitHub Desktop.
Binary Search Tree
class Node:
def __init__(self, name, value):
self.name = name
self.value = value
self.right = None
self.left = None
"""
Updating the BST
In order to add a new Child Node to the Root, examine the value of the new Node.
If NewNode.value > RootNode.value, then new Node becomes the right Child Node of the Root.
If NewNode.value < RootNode.value, then new Node becomes theleft Child Node of the Parent.
If the right Child Node and the left Child Node already exist, we make the new Node a respective Child of the Parent's Child Node.
"""
def add(self, value):
if not value == self.value:
if value > self.value:
if not self.right:
self.right = Node(None, value)
else:
self.right.add(value)
elif value < self.value:
if not self.left:
self.left = Node(None, value)
else:
self.left.add(value)
else:
raise ValueError('Duplicate value')
else:
raise ValueError('Duplicate value')
"""
Searching the Binary Tree is straightforward.
If the required value == to the value of the Root Node, return True.
If the required value > than the value of the Root Node, search the right Child Node of the Root Node.
If the required value < than the value of the Root Node, search the left Child Node of the Root Node.
If the above conditions did not meet, search the Children of the Children recursively.
If we reach the end of the Binary Tree and, it means there are not any Nodes to check - we throw an Exception to terminate the recursion.
"""
def find(self, value):
if value == self.value:
return True
elif value > self.value:
if not self.right:
raise Exception
self.right.find(value)
elif value < self.value:
if not self.left:
raise Exception
self.left.find(value)
class BinaryTree:
def __init__(self, root_value):
self.root = Node('root', root_value)
def add(self, value):
self.root.add(value)
def __repr__(self):
return str(self.root.name)
def find(self, value):
try:
self.root.find(value)
except Exception:
return False
else:
return True
bst = BinaryTree(root_value=90)
bst.add(95)
bst.add(66)
bst.add(13)
bst.add(100)
bst.find(20)
bst.find(13)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment