Skip to content

Instantly share code, notes, and snippets.

@tgroshon
Created June 2, 2014 13:35
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 tgroshon/f2aa260b0331b39f3dba to your computer and use it in GitHub Desktop.
Save tgroshon/f2aa260b0331b39f3dba to your computer and use it in GitHub Desktop.
Naive Python Tree Implementation for demonstration purposes.
class Node:
'''
Simple implementation of a tree. Functions for add(), search(), and size().
'''
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def add(self, data):
'''Add data to tree. Internally creates a new node.'''
if data < self.value:
if self.left is None:
self.left = Node(data)
else:
self.left.add(data)
else:
if self.right is None:
self.right = Node(data)
else:
self.right.add(data)
def search(self, query):
'''Return node with matching value.'''
if query == self.value:
return self
elif query < self.value:
if self.left is None:
raise Exception('Node not found')
return self.left.search(query)
else:
if self.right is None:
raise Exception('Node not found')
return self.right.search(query)
def size(self):
'''Get the size of all nodes.'''
stack = []
count = 1 # 1 for this node
if self.left:
stack.append(self.left)
count += 1
if self.right:
stack.append(self.right)
count += 1
while len(stack) != 0:
node = stack.pop(0)
if node.left:
stack.append(node.left)
count += 1
if node.right:
stack.append(node.right)
count += 1
return count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment