Skip to content

Instantly share code, notes, and snippets.

@sean-duffy
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sean-duffy/bcd9b952cd0cffae7084 to your computer and use it in GitHub Desktop.
Save sean-duffy/bcd9b952cd0cffae7084 to your computer and use it in GitHub Desktop.
class Node:
def __init__(self, n):
self.n = n
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self, node=None):
self.head = node
def add(self, node):
if self.head == None:
self.head = node
else:
if node.n > self.head.n:
self.head.right = BinarySearchTree(self.head.right).add(node).head
else:
self.head.left = BinarySearchTree(self.head.left).add(node).head
return self
def search(self, n):
if self.head == None:
return None
if self.head.n == n:
return self.head
elif n > self.head.n:
return BinarySearchTree(self.head.right).search(n)
else:
return BinarySearchTree(self.head.left).search(n)
def print_in_order(self):
if self.head != None:
BinarySearchTree(self.head.left).print_in_order()
print self.head.n
BinarySearchTree(self.head.right).print_in_order()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment