Skip to content

Instantly share code, notes, and snippets.

@travcunn
Last active December 23, 2015 06:09
Show Gist options
  • Save travcunn/6592030 to your computer and use it in GitHub Desktop.
Save travcunn/6592030 to your computer and use it in GitHub Desktop.
Binary Tree Search
class Tree(object):
def __init__(self, root_node=None):
self.root = root_node
self.__size = 0
def delete(self, value):
node = self._search(self.root, value)
if node is False:
raise ValueError("%s not found in the tree" % value)
self._delete(node)
def _delete(self, node):
#TODO: make this work
pass
def insert(self, value):
new_node = Node(value)
new_parent = None
new_location = self.root
while new_location is not None:
new_parent = new_location
if new_node.value < new_location.value:
new_location = new_location.left
else:
new_location = new_location.right
new_node.parent = new_parent
if new_parent is None:
self.root = new_node
elif new_node.value <= new_parent.value:
new_parent.left = new_node
else:
new_parent.right = new_node
self.__size += 1
def fromlist(self, list):
for item in list:
self.insert(item)
def min(self, start_node=None, get_node=False):
if start_node is None:
start_node = self.root
if start_node is None:
return None
left_node = start_node
while left_node.left is not None:
left_node = left_node.left
if get_node:
return left_node
return left_node.value
def max(self, start_node=None, get_node=False):
if start_node is None:
start_node = self.root
if start_node is None:
return None
right_node = start_node
while right_node.right is not None:
right_node = right_node.right
if get_node:
return right_node
return right_node.value
def inorder_traversal(self, start_node=None):
if start_node is None:
if self.root is not None:
node = self.root
else:
return None
self._inorder_traversal(node)
def _inorder_traversal(self, node):
if node is not None:
self._inorder_traversal(node.left)
print(node.value)
self._inorder_traversal(node.right)
def preorder_traversal(self, start_node=None):
if start_node is None:
if self.root is not None:
node = self.root
else:
return None
self._preorder_traversal(node)
def _preorder_traversal(self, node):
if node is not None:
print(node.value)
self._preorder_traversal(node.left)
self._preorder_traversal(node.right)
def _search(self, node, value):
if node is None:
return False
if value < node.value:
return self._search(node.left, value)
elif value > node.value:
return self._search(node.right, value)
else:
return node
def __contains__(self, value):
if self._search(self.root, value):
return True
else:
return False
def __len__(self):
return self.__size
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.parent = None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment