Skip to content

Instantly share code, notes, and snippets.

@monicatoth
Created September 6, 2013 06:27
Show Gist options
  • Save monicatoth/6460217 to your computer and use it in GitHub Desktop.
Save monicatoth/6460217 to your computer and use it in GitHub Desktop.
Creates a complete (a.k.a. "perfect") binary tree from a given array.
# Sample array
alpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']
# Note from Alan:
# the array will always be the right length to produce
# a balanced tree where every node has two children.
# Decided on a list representation
# The end result will look like: [['A', ['B', 'I']], ['B', ['C', 'F']] . . . ]
final_tree = []
# Siblings are determined as a function of their depth and
# the index number they were assigned in the initial array.
def tree_metadata(alpha):
index_interval = []
i = len(alpha)
while i > 1:
i = (i - 1)/2
index_interval.append(i) # final output: [7, 3, 1]
return index_interval
def get_children(parent, depth):
index_interval = tree_metadata(alpha)
i = alpha.index(parent)
left_child = alpha[i + 1]
right_child = alpha[i + 1 + index_interval[depth]]
# print [parent, [left_child, right_child]] # test
final_tree.append([parent, [left_child, right_child]])
if depth < (len(index_interval) - 1): # excludes leaf nodes
for item in [left_child, right_child]:
get_children(item, depth + 1)
return final_tree
if __name__ == "__main__":
result = get_children(alpha[0], 0)
for element in result:
print element
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment