The idea is to store the elements of the tree in an array using inorder traversal. Inorder traversal of a BST produces a sorted array. Once we have a sorted array, recursively construct a balanced BST by picking the middle element of the array as the root for each subtree.
Follow the steps below to solve the problem:
Traverse given BST in inorder and store result in an array. 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 in Sorted Array to Balanced BST.
C++
//Driver Code Starts// C++ program to convert a left unbalanced BST to// a balanced BST#include<iostream>#include<vector>#include<queue>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intvalue){data=value;left=nullptr;right=nullptr;}};//Driver Code Ends// Inorder traversal to store elements of the// tree in sorted ordervoidstoreInorder(Node*root,vector<int>&nodes){if(root==nullptr)return;// Traverse the left subtreestoreInorder(root->left,nodes);// Store the node datanodes.push_back(root->data);// Traverse the right subtreestoreInorder(root->right,nodes);}// Function to build a balanced BST from a sorted arrayNode*buildBalancedTree(vector<int>&nodes,intstart,intend){// Base caseif(start>end)returnnullptr;// Get the middle element and make it the rootintmid=(start+end)/2;Node*root=newNode(nodes[mid]);// Recursively build the left and right subtreesroot->left=buildBalancedTree(nodes,start,mid-1);root->right=buildBalancedTree(nodes,mid+1,end);returnroot;}// Function to balance a BSTNode*balanceBST(Node*root){vector<int>nodes;// Store the nodes in sorted orderstoreInorder(root,nodes);// Build the balanced tree from the sorted nodesreturnbuildBalancedTree(nodes,0,nodes.size()-1);}//Driver Code Starts// Print tree as level ordervoidprintLevelOrder(Node*root){if(root==nullptr){cout<<"N ";return;}queue<Node*>qq;qq.push(root);intnonNull=1;while(!qq.empty()&&nonNull>0){Node*curr=qq.front();qq.pop();if(curr==nullptr){cout<<"N ";continue;}nonNull--;cout<<(curr->data)<<" ";qq.push(curr->left);qq.push(curr->right);if(curr->left)nonNull++;if(curr->right)nonNull++;}}intmain(){// Constructing an unbalanced BST// 4// / \ // 3 5// / \ // 2 6// / \ // 1 7Node*root=newNode(4);root->left=newNode(3);root->left->left=newNode(2);root->left->left->left=newNode(1);root->right=newNode(5);root->right->right=newNode(6);root->right->right->right=newNode(7);Node*balancedRoot=balanceBST(root);printLevelOrder(balancedRoot);return0;}//Driver Code Ends
Java
//Driver Code Starts// Java program to convert a left unbalanced BST to// a balanced BSTimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intvalue){data=value;left=null;right=null;}}classGFG{//Driver Code Ends// Inorder traversal to store elements of the// tree in sorted orderstaticvoidstoreInorder(Noderoot,ArrayList<Integer>nodes){if(root==null)return;// Traverse the left subtreestoreInorder(root.left,nodes);// Store the node datanodes.add(root.data);// Traverse the right subtreestoreInorder(root.right,nodes);}// Function to build a balanced BST from a sorted arraystaticNodebuildBalancedTree(ArrayList<Integer>nodes,intstart,intend){// Base caseif(start>end)returnnull;// Get the middle element and make it the rootintmid=(start+end)/2;Noderoot=newNode(nodes.get(mid));// Recursively build the left and right subtreesroot.left=buildBalancedTree(nodes,start,mid-1);root.right=buildBalancedTree(nodes,mid+1,end);returnroot;}// Function to balance a BSTstaticNodebalanceBST(Noderoot){ArrayList<Integer>nodes=newArrayList<>();// Store the nodes in sorted orderstoreInorder(root,nodes);// Build the balanced tree from the sorted nodesreturnbuildBalancedTree(nodes,0,nodes.size()-1);}//Driver Code Starts// Print tree as level orderstaticvoidprintLevelOrder(Noderoot){if(root==null){System.out.print("N ");return;}Queue<Node>qq=newLinkedList<>();qq.add(root);intnonNull=1;while(!qq.isEmpty()&&nonNull>0){Nodecurr=qq.poll();if(curr==null){System.out.print("N ");continue;}nonNull--;System.out.print(curr.data+" ");qq.add(curr.left);qq.add(curr.right);if(curr.left!=null)nonNull++;if(curr.right!=null)nonNull++;}}publicstaticvoidmain(String[]args){// Constructing an unbalanced BST// 4// / \// 3 5// / \// 2 6// / \// 1 7Noderoot=newNode(4);root.left=newNode(3);root.left.left=newNode(2);root.left.left.left=newNode(1);root.right=newNode(5);root.right.right=newNode(6);root.right.right.right=newNode(7);NodebalancedRoot=balanceBST(root);printLevelOrder(balancedRoot);}}//Driver Code Ends
Python
#Driver Code Starts# Python program to convert a left unbalanced BST to# a balanced BSTclassNode:def__init__(self,value):self.data=valueself.left=Noneself.right=None#Driver Code Ends# Inorder traversal to store elements of the# tree in sorted orderdefstoreInorder(root,nodes):ifrootisNone:return# Traverse the left subtreestoreInorder(root.left,nodes)# Store the node datanodes.append(root.data)# Traverse the right subtreestoreInorder(root.right,nodes)# Function to build a balanced BST from a sorted arraydefbuildBalancedTree(nodes,start,end):# Base caseifstart>end:returnNone# Get the middle element and make it the rootmid=(start+end)//2root=Node(nodes[mid])# Recursively build the left and right subtreesroot.left=buildBalancedTree(nodes,start,mid-1)root.right=buildBalancedTree(nodes,mid+1,end)returnroot# Function to balance a BSTdefbalanceBST(root):nodes=[]# Store the nodes in sorted orderstoreInorder(root,nodes)# Build the balanced tree from the sorted nodesreturnbuildBalancedTree(nodes,0,len(nodes)-1)#Driver Code Starts# Print tree as level orderfromcollectionsimportdequedefprintLevelOrder(root):ifrootisNone:print("N",end=" ")returnqueue=deque([root])nonNull=1whilequeueandnonNull>0:curr=queue.popleft()ifcurrisNone:print("N",end=" ")continuenonNull-=1print(curr.data,end=" ")queue.append(curr.left)queue.append(curr.right)ifcurr.left:nonNull+=1ifcurr.right:nonNull+=1if__name__=="__main__":root=Node(4)root.left=Node(3)root.left.left=Node(2)root.left.left.left=Node(1)root.right=Node(5)root.right.right=Node(6)root.right.right.right=Node(7)balancedRoot=balanceBST(root)printLevelOrder(balancedRoot)#Driver Code Ends
C#
//Driver Code Starts// C# program to convert a left unbalanced BST to// a balanced BSTusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intvalue){data=value;left=null;right=null;}}classGFG{//Driver Code Ends// Inorder traversal to store elements of the// tree in sorted orderstaticvoidstoreInorder(Noderoot,List<int>nodes){if(root==null)return;// Traverse the left subtreestoreInorder(root.left,nodes);// Store the node datanodes.Add(root.data);// Traverse the right subtreestoreInorder(root.right,nodes);}// Function to build a balanced BST from a sorted arraystaticNodebuildBalancedTree(List<int>nodes,intstart,intend){// Base caseif(start>end)returnnull;// Get the middle element and make it the rootintmid=(start+end)/2;Noderoot=newNode(nodes[mid]);// Recursively build the left and right subtreesroot.left=buildBalancedTree(nodes,start,mid-1);root.right=buildBalancedTree(nodes,mid+1,end);returnroot;}// Function to balance a BSTstaticNodebalanceBST(Noderoot){List<int>nodes=newList<int>();// Store the nodes in sorted orderstoreInorder(root,nodes);// Build the balanced tree from the sorted nodesreturnbuildBalancedTree(nodes,0,nodes.Count-1);}//Driver Code Starts// Print tree as level orderstaticvoidprintLevelOrder(Noderoot){if(root==null){Console.Write("N ");return;}Queue<Node>qq=newQueue<Node>();qq.Enqueue(root);intnonNull=1;while(qq.Count>0&&nonNull>0){Nodecurr=qq.Dequeue();if(curr==null){Console.Write("N ");continue;}nonNull--;Console.Write(curr.data+" ");qq.Enqueue(curr.left);qq.Enqueue(curr.right);if(curr.left!=null)nonNull++;if(curr.right!=null)nonNull++;}}staticvoidMain(){// Constructing an unbalanced BST// 4// / \// 3 5// / \// 2 6// / \// 1 7Noderoot=newNode(4);root.left=newNode(3);root.left.left=newNode(2);root.left.left.left=newNode(1);root.right=newNode(5);root.right.right=newNode(6);root.right.right.right=newNode(7);NodebalancedRoot=balanceBST(root);printLevelOrder(balancedRoot);}}//Driver Code Ends
JavaScript
//Driver Code Starts// JavaScript program to convert a left unbalanced BST to// a balanced BSTclassNode{constructor(value){this.data=value;this.left=null;this.right=null;}}//Driver Code Ends// Inorder traversal to store elements of the// tree in sorted orderfunctionstoreInorder(root,nodes){if(root===null)return;// Traverse the left subtreestoreInorder(root.left,nodes);// Store the node datanodes.push(root.data);// Traverse the right subtreestoreInorder(root.right,nodes);}// Function to build a balanced BST from a sorted arrayfunctionbuildBalancedTree(nodes,start,end){// Base caseif(start>end)returnnull;// Get the middle element and make it the rootletmid=Math.floor((start+end)/2);letroot=newNode(nodes[mid]);// Recursively build the left and right subtreesroot.left=buildBalancedTree(nodes,start,mid-1);root.right=buildBalancedTree(nodes,mid+1,end);returnroot;}// Function to balance a BSTfunctionbalanceBST(root){letnodes=[];// Store the nodes in sorted orderstoreInorder(root,nodes);// Build the balanced tree from the sorted nodesreturnbuildBalancedTree(nodes,0,nodes.length-1);}//Driver Code Starts// Print tree as level orderfunctionprintLevelOrder(root){if(root===null){console.log("N");return;}letqueue=[];queue.push(root);letnonNull=1;while(queue.length>0&&nonNull>0){letcurr=queue.shift();if(curr===null){process.stdout.write("N ");continue;}nonNull--;process.stdout.write(curr.data+" ");queue.push(curr.left);queue.push(curr.right);if(curr.left)nonNull++;if(curr.right)nonNull++;}}// Driver Code// Constructing an unbalanced BST// 4// / \// 3 5// / \// 2 6// / \// 1 7letroot=newNode(4);root.left=newNode(3);root.left.left=newNode(2);root.left.left.left=newNode(1);root.right=newNode(5);root.right.right=newNode(6);root.right.right.right=newNode(7);letbalancedRoot=balanceBST(root);printLevelOrder(balancedRoot);//Driver Code Ends
Output
4 2 6 1 3 5 7
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), as 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.