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 firstname.lastname@example.org. 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.
- Find a pair with given sum in a Balanced BST
- Sorted Array to Balanced BST
- Pairs involved in Balanced Parentheses
- Split a BST into two balanced BSTs based on a value K
- Find if there is a triplet in a Balanced BST that adds to zero
- Sorted Linked List to Balanced BST
- How to determine if a binary tree is height-balanced?
- Merge Two Balanced Binary Search Trees
- Check if the Binary Tree contains a balanced BST of size K
- Count Balanced Binary Trees of Height h
- Practice questions on Height balanced/AVL Tree
- Create Balanced Binary Tree using its Leaf Nodes without using extra space
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Convert BST to Min Heap
- Convert BST to Max Heap
- Convert BST into a Min-Heap without using array
- Convert a tree to forest of even nodes
- Convert Directed Graph into a Tree
- Convert left-right representation of a binary tree to down-right
- Convert Ternary Expression to a Binary Tree