Balanced binary search tree from sorted list
Given a sorted list (or a sorted array) as input, generate a balanced binary search tree in O(n)
Iteratively extracting every single element from the list/array and inserting it into a balanced binary search tree implementation (e.g. red/black trees) won’t work since it’s \( O(N \log{N}) \). A better solution would be to recursively create the left and right subtrees from the bottom up and inserting the subtrees’ roots each time by advancing a single pointer in the list.
The algorithm that will be presented might come in handy also to solve problems like joining balanced binary search trees in \( O(n+m) \) since one could do an in-order traversal of the first and second tree and store the results in two arrays, then combine the two sorted arrays (\( O(n+m) \)) and finally use this algorithm to generate a balanced binary search tree in \( O(n+m) \) yielding a grand total of \( O(n+m) \) as requested.
Pseudocode and code follow
recursiveCreateBST(pointer_to_first_element, number_of_nodes_in_the_tree)
if(number_of_nodes_in_the_tree == 0)
return NULL // no node was inserted for a degenerate tree
leftSubtree = recursiveCreateBST(pointer_to_first_element,
number_of_nodes_in_the_tree / 2)
root = createRootNode(pointer_to_first_element)
root.left = leftSubtree
pointer_to_second_element = advance_pointer(pointer_to_first_element)
root.right = recursiveCreateBST(pointer_to_second_element,
number_of_nodes_in_the_tree - (leftSubtree.size) - 1)
return root
This code can safely be used to build from the bottom up a balanced BST from either a sorted list or a sorted array. The iterative in-order print is taken from this article.
The complexity of the algorithm in sortedListToBST
can be calculated with Master theorem. The problem is in the form
with the assumptions of \( a = 2, \ b = 2 \). Since
\[\quad f(n) \in O\left( n^{\log_b a - \varepsilon} \right)\](\( f(n) \in O(1) \)), therefore it holds
\[\quad T(n) \in \Theta\left( n^{\log_b a} \right)\]and the algorithm is \( O(n) \) as expected.