Skip to content

Instantly share code, notes, and snippets.

@peterdcasey
Created November 13, 2019 08:16
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 peterdcasey/d57e89528dcb7998739e089d185bbc99 to your computer and use it in GitHub Desktop.
Save peterdcasey/d57e89528dcb7998739e089d185bbc99 to your computer and use it in GitHub Desktop.
BinaryTree implementation using Python lists
"""
BinaryTree code using Python Lists
[5, [4, [], []], []]
[3, [9, [4, [], []], []], [7, [], [6, [], []]]]
[3, [9, [11, [4, [], []], []], []], [7, [], [6, [], []]]]
[6, [], []]
"""
def BinaryTree(r):
return [r, [], []]
def insertLeft(root, newBranch):
left_child = getLeftChild(root)
set_left_child(root, [newBranch, left_child, []])
return root
def insertRight(root, newBranch):
right_child = getRightChild(root)
set_right_child(root, [newBranch, [], right_child])
return root
def getRootVal(root):
return root[0]
def setRootVal(root,newVal):
root[0] = newVal
def set_right_child(root, branch):
root[2] = branch
def set_left_child(root, branch):
root[1] = branch
def getLeftChild(root):
return root[1]
def getRightChild(root):
return root[2]
r = BinaryTree(3)
insertLeft(r,4)
insertLeft(r,5)
insertRight(r,6)
insertRight(r,7)
l = getLeftChild(r)
print(l)
setRootVal(l,9)
print(r)
insertLeft(l,11)
print(r)
print(getRightChild(getRightChild(r)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment