Hey i am preparing for exams and i could use some help. The task is to build a binary sum tree (parent node key is a sum of children keys) from an array of values of leaves (left to right) which is always 2^n long. I first transform the array to an array of nodes. Then i have made a recursive function that combines pairs and calls itself on a new array of created nodes. Is there a better way of doing this task? maybe one that is "in place"? e.g.
input: [1,2,3,4]
output:
10 / \ 3 7 / \ / \ 1 2 3 4
class SumTree:
def __init__(self):
self.root = None
class Node:
def __init__(self):
self.key = 0
self.parent = None
self.left = None
self.right = None
def makeNode(key):
n = Node()
n.key = key
return n
def buildSumTree(array):
for i in range(len(array)):
array[i] = makeNode(array[i])
tree = SumTree()
tree.root = buildSumTree_rec(array)
return tree
def buildSumTree_rec(array):
if len(array) == 1 :
return array[0]
else:
a = []
for i in range(0, len(array) // 2, 2):
n = makeNode(array[i].key + array[i + 1].key)
n.left = array[i]
n.right = array[i + 1]
array[i].parent = n
array[i + 1].parent = n
a.append(n)
return buildSumTree_rec(a)