I am trying to create an algorithm that creates a complete binary search tree, given a list of values. Complete that all levels are complete, with the possible exception of the last level, which should have all the elements shifted as far as possible.
I implemented something (in Python) that would create a balanced BST, for example:
# TreeNode constructor takes (data, left, right, parent) def make_tree(arr, parent): if not arr: return None length = len(arr) if length == 1: return TreeNode(arr[0], None, None, parent) else: mid = int(len(arr)/2) mid_node = TreeNode(arr[mid], None, None, parent) mid_node.left = make_tree(arr[0:mid], mid_node) mid_node.right = make_tree(arr[mid+1:length], mid_node) return mid_node
It works by recursively breaking the list by midpoint and making the middle the parent node.
However, this does not create a complete BST. Given the list [2,4,7,8,10], he will create this:
7 / \ 4 10 / / 2 8
But the full BST will look like this:
8 / \ 4 10 / \ 2 7
Do you have any suggestions on how to change my approach to achieve this?