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
An Efficient Solution can construct 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
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 email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Sorted Linked List to Balanced BST
- Sorted Array to Balanced BST
- Find if there is a triplet in a Balanced BST that adds to zero
- Check if the Binary Tree contains a balanced BST of size K
- Find a pair with given sum in a Balanced BST
- Split a BST into two balanced BSTs based on a value K
- Two nodes of a BST are swapped, correct the BST | Set-2
- K'th Largest Element in BST when modification to BST is not allowed
- Find k-th smallest element in BST (Order Statistics in BST)
- Two nodes of a BST are swapped, correct the BST
- Convert BST into a Min-Heap without using array
- Convert BST to Min Heap
- Convert BST to Max Heap
- Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
- How to determine if a binary tree is height-balanced?
- Merge Two Balanced Binary Search Trees
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Count Balanced Binary Trees of Height h
- Practice questions on Height balanced/AVL Tree
- Pairs involved in Balanced Parentheses