def buildTree(numbers, availableSpace, total, previousNode): tree = [] nodeIsValid = True # print initial status numberOfItems = len(numbers) print(" ") print("numbers: ", numbers) print( "calculating the possible combinations: for a maximum capacity of %i" % availableSpace) if (numberOfItems == 0): print("skipping empty list of numbers") node = [] elif (numberOfItems == 1): value = numbers[0] # recalculate available and used space if (availableSpace >= value): availableSpace = availableSpace - value total = total + value else: # the required space is too small nodeIsValid = False # initiate a new node node = TreeNode(value, availableSpace, total) print("added new node:", value) if (nodeIsValid == False): print("node is invalid") node.setInvalid() else: node.setValid() print("available space left: %i" % availableSpace) print("space in use:", total) else: # calculate the middlest item nodePosition = int(numberOfItems / 2) value = numbers[nodePosition] # recalculate available and used space if (availableSpace >= value): availableSpace = availableSpace - value total = total + value else: # the required space is too small nodeIsValid = False # initiate this node as a new node node = TreeNode(value, availableSpace, total) print("added new node:", value) if (nodeIsValid == False): print("node is invalid") node.setInvalid() else: node.setValid() print("available space left: %i" % availableSpace) print("space in use:", total) # calculate subtree for the numbers left of the node value leftSubtree = buildTree(numbers[0:nodePosition], availableSpace, total, node) if (len(leftSubtree)): firstNode = leftSubtree[0] if isinstance(firstNode, TreeNode): if (firstNode.isInvalidNode()): # invalid nodes belong to the right side node.setRight(leftSubtree) else: # valid nodes belong to the left side node.setLeft(leftSubtree) # calculate subtree for the numbers right of the node value if (nodePosition < numberOfItems): rightSubtree = buildTree(numbers[nodePosition + 1:], availableSpace, total, node) else: rightSubtree = [] if (len(rightSubtree)): firstNode = rightSubtree[0] if isinstance(firstNode, TreeNode): if (firstNode.isInvalidNode()): # invalid nodes belong to the right side node.setRight(rightSubtree) else: # valid nodes belong to the left side node.setLeft(rightSubtree) # add the newly built node to the tree tree.append(node) print(tree) return tree