Created
November 13, 2019 08:16
-
-
Save peterdcasey/d57e89528dcb7998739e089d185bbc99 to your computer and use it in GitHub Desktop.
BinaryTree implementation using Python lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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