Given an unsorted integer array that represents binary search tree (BST) keys, construct a height-balanced BST from it. For each node of a height-balanced tree, the difference between its left and right subtree height is at most 1.

For example,

Input: keys = [15, 10, 20, 8, 12, 16, 25]
 
Output:
 
       15
     /    \
    10     20
   /  \   /  \
  8   12 16  25
 
OR
 
       12
     /    \
    10    20
   /     /  \
  8     16  25
       /
      15
 
OR
 
Any other possible representation.

Practice this problem

We have already discussed how to insert a key into a BST. The height of such BST in the worst-case can be as much as the total number of keys in the BST. The worst case happens when given keys are sorted in ascending or descending order, and we get a skewed tree where all the nodes except the leaf have one and only one child.

For height-balanced BSTs, with each comparison, skip about half of the tree so that each insertion operation takes time proportional to the logarithm of the total number of items n stored in the tree, i.e., log2n. This is much better than the linear time required to find items by key in an (unsorted) array or unbalanced trees.

 
We can easily modify the solution to get height-balanced BSTs if all keys are known in advance. The idea is to sort the given keys first. Then the root will be the middle element of the sorted array, and we recursively construct the left subtree of the root by keys less than the middle element and the right subtree of the root by keys more than the middle element. For example,

Array to Balanced BST

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

8 10 12 15 16 20 25

Java


Download  Run Code

Output:

8 10 12 15 16 20 25

Python


Download  Run Code

Output:

8 10 12 15 16 20 25

The time complexity of the above solution is O(n.log(n)), where n is the size of the BST, and requires space proportional to the tree’s height for the call stack.