Convert a normal BST to Balanced BST
Given a BST (Binary Search Tree) that may be unbalanced, convert it into a balanced BST that has minimum possible height.
Input: 30 / 20 / 10 Output: 20 / \ 10 30 Input: 4 / 3 / 2 / 1 Output: 3 3 2 / \ / \ / \ 1 4 OR 2 4 OR 1 3 OR .. \ / \ 2 1 4 Input: 4 / \ 3 5 / \ 2 6 / \ 1 7 Output: 4 / \ 2 6 / \ / \ 1 3 5 7
A Simple Solution is to traverse nodes in Inorder and one by one insert into a self-balancing BST like AVL tree. Time complexity of this solution is O(n Log n) and this solution doesn’t guarantee the minimum possible height as in the worst case the height of the AVL tree can be 1.44*log2n.
An Efficient Solution can be to construct a balanced BST in O(n) time with minimum possible height. Below are steps.
- Traverse given BST in inorder and store result in an array. This step takes O(n) time. Note that this array would be sorted as inorder traversal of BST always produces sorted sequence.
- Build a balanced BST from the above created sorted array using the recursive approach discussed here. This step also takes O(n) time as we traverse every element exactly once and processing an element takes O(1) time.
Below is the implementation of above steps.
Preorder traversal of balanced BST is : 7 5 6 8 10
Time Complexity: O(n), As we are just traversing the tree twice. Once in inorder traversal and then in construction of the balanced tree.
Auxiliary space: O(n), The extra space is used to store the nodes of the inorder traversal in the vector. Also the extra space taken by recursion call stack is O(h) where h is the height of the tree.
This article is contributed Aditya Goel. If you likeGeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Login to comment...