Skip to content

Instantly share code, notes, and snippets.

@ttowncompiled
Last active May 21, 2017 07:38
Show Gist options
  • Save ttowncompiled/c41f9c03ef1037ac23fa9f68f5d5b21e to your computer and use it in GitHub Desktop.
Save ttowncompiled/c41f9c03ef1037ac23fa9f68f5d5b21e to your computer and use it in GitHub Desktop.
A BinarySearchTree to use for HackerRank problems.
###
# Python 3
# T = [int, BinarySearchTree, BinarySearchTree, int] or None
###
def size(T):
return T[3] if not T is None else 0
def is_empty(T):
return T is None
def v(T):
return T[0]
def left(T):
return T[1]
def right(T):
return T[2]
def insert(T, x):
if T is None:
return [x, None, None, 1]
if x == T[0]:
return T
T[3] += 1
if x < T[0]:
T[1] = insert(T[1], x)
else:
T[2] = insert(T[2], x)
return T
def remove(T, x):
if T is None:
return None
if x == T[0]:
if T[1] is None and T[2] is None:
return None
if not T[1] is None:
T[0] = T[1][0]
T[3] -= T[1][3]
T[1] = remove(T[1], T[1][0])
T[3] += T[1][3] if not T[1] is None else 0
else:
T[0] = T[2][0]
T[3] -= T[2][3]
T[2] = remove(T[2], T[2][0])
T[3] += T[2][3] if not T[2] is None else 0
elif x < T[0]:
T[3] -= T[1][3] if not T[1] is None else 0
T[1] = remove(T[1], x)
T[3] += T[1][3] if not T[1] is None else 0
else:
T[3] -= T[2][3] if not T[2] is None else 0
T[2] = remove(T[2], x)
T[3] += T[2][3] if not T[2] is None else 0
return T
# The End
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment