I am trying to make an algorithm that creates a complete binary search tree given a list of values. Complete, in that all levels are full except for maybe the last level, which needs to have all elements shifted as far left as possible.
I've implemented something (in Python) that will create a balanced BST, like this:
# 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 splitting the list by the midpoint, and making the midpoint a parent node.
However, this does not create a complete BST. Given the list [2,4,7,8,10], it will create this:
7
/ \
4 10
/ /
2 8
But a complete BST would look like this:
8
/ \
4 10
/ \
2 7
Do you have any suggestions on how to modify my approach to accomplish this?