Skip to content

Instantly share code, notes, and snippets.

@aaronjwood
Created November 15, 2015 02:37
Show Gist options
  • Save aaronjwood/916cbe6bd97b5ec41f6c to your computer and use it in GitHub Desktop.
Save aaronjwood/916cbe6bd97b5ec41f6c to your computer and use it in GitHub Desktop.
Binary search tree implementation in Python
import time
import random
class Node:
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
def insert(root, v):
if root is None:
root = Node(v, None, None)
elif v < root.value:
root.left = insert(root.left, v)
else:
root.right = insert(root.right, v)
return root
def traverse(root):
if root is None:
return
traverse(root.left)
traverse(root.right)
if __name__ == "__main__":
root = None
SIZE = 2000000
a = []
print("Generating random array with %s values..." % SIZE)
start = time.clock()
for i in range(SIZE):
a.append(random.randint(1, 10000))
end = time.clock() - start
print("Done. Took %s seconds\n" % end)
print("Filling the tree with %s nodes..." % SIZE)
start = time.clock()
for i in range(SIZE):
root = insert(root, a[i])
end = time.clock() - start
print("Done. Took %s seconds\n" % end)
print("Traversing all %s nodes in tree..." % SIZE)
start = time.clock()
traverse(root)
end = time.clock() - start
print("Done. Took %s seconds\n" % end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment