Given a binary search tree (BST), convert it into a height-balanced binary search tree.

For a height-balanced binary search tree, the difference between the height of the left and right subtree of every node is never more than 1. The height of a binary search tree with n nodes is never more than log2(n) + 1.

 
For example, convert BST on the left into a BST on the right:

Height Balanced BST

Practice this problem

The idea is to traverse the BST in an inorder fashion and store all encountered nodes in a container (array, list, vector, etc.). The container will be sorted since inorder traversal on a BST always visits the nodes in increasing order of their values.

Then construct a height-balanced BST from the sorted nodes. The idea is to start from the middle element of the sorted array. That would be our root node of the BST. All elements before the middle element should go in the left subtree, and all elements after the middle element should go in the right subtree. We can easily do this recursively, and we will end up with a height-balanced BST.

 
The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Preorder traversal of the constructed BST is 8 2 5 15 10 20

Java

Python

The time complexity of the above solution is O(n), where n is the size of the BST. However, the program requires O(n) extra space for storing the BST nodes.

We can do the conversion in-place without any auxiliary data structure. The idea is to convert the given BST into a sorted doubly linked list and then construct a height-balanced BST from it. This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

Preorder traversal of the constructed BST is 2 5 8 10 15 20

Java

Python