Normal BST to Balanced BST | Practice | GeeksforGeeks

Given a Binary Search Tree, modify the given BST such that itis balanced and has minimum possible height.
Examples :
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 


Your Task:
The task is to complete the function buildBalancedTree() which takes root as the input argument, and returns the root of tree after converting the given BST into a balanced BST that has minimum possible height. The driver code will print the height of the updated tree in output itself. 
 
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Here N denotes total number of nodes in given BST.

Constraints:
1<=N<=200
0
vikasanwla
This comment was deleted.
0
mishraanuyesh71 month ago
class GfG{   static void inorder(Node root, ArrayList<Integer> list){       if(root==null) return;       inorder(root.left,list);       list.add(root.data);       inorder(root.right,list);   }   static Node makeTree(ArrayList<Integer> list,int l, int r){       if(l>r) return null;       int mid = l + (r-1)/2;       int data = list.get(mid);      Node lc=makeTree(list,l,mid-1); Node rc=makeTree(list,mid+1,r);   Node node=new Node(data); node.left=lc; node.right=rc; return node;   }   Node buildBalancedTree(Node root)    {       if(root == null){           return root;       }       ArrayList<Integer> list = new ArrayList<>();       inorder(root,list);       return makeTree(list,0,list.size()-1);       //Add your code here.          }}
+1
gaurabhkumarjha271020011 month ago
void inorder (Node* root, vector <Node* > &v){
        
         if (!root) return;
        
        inorder (root->left, v);
        v.push_back (root);
        inorder (root->right, v);
    }
Node* cons (Node* root, vector <Node*> &common, int low, int high){
         
      if (low > high) return nullptr;
         
        int  mid= low+ (high-low)/2;
        root= common[mid];
        
    root->left= cons (root, common, low, mid-1);
    root->right= cons (root, common, mid+1, high);
         
      return root;
  }
Node* buildBalancedTree(Node* root)
{

	    if (!root) return root;
        vector <Node*> v;
        inorder(root, v);
  return cons (root, v, 0, v.size()-1);
    
}

0
detroix071 month ago
Node* BST(vector<int>InOrder,int n,int InOrderStart,int InOrderEnd){  if(InOrderStart>InOrderEnd) return NULL;  int mid=(InOrderStart+InOrderEnd)/2;  Node* root=new Node(InOrder[mid]);  root->left=BST(InOrder,n,InOrderStart,mid-1);  root->right=BST(InOrder,n,mid+1,InOrderEnd);  return root;}
 
void InOrderTraversal(Node* root,vector<int> &InOrder){   if(root==NULL) return;   InOrderTraversal(root->left,InOrder);   InOrder.push_back(root->data);   InOrderTraversal(root->right,InOrder);}
 
Node* buildBalancedTree(Node* root){vector<int> InOrder;InOrderTraversal(root,InOrder);int n = InOrder.size();Node* ans = BST(InOrder,n,0,n-1);return ans;} 
0
adityasingh1091 month ago
void inorder(Node* root, vector<int> &in){
    if(root == nullptr)
        return;
    inorder(root->left, in);
    in.push_back(root->data);
    inorder(root->right, in);
}

Node* inorderToBst(int s , int e, vector<int> &in){
    if(s>e)
        return NULL;
    int mid = (s+e) /2;
    
    Node* root = new Node(in[mid]);
    root->left = inorderToBst(s,mid-1,in);
    root->right = inorderToBst(mid +1, e, in);
}

Node* buildBalancedTree(Node* root)
{
    vector<int> bst;
    inorder(root, bst);
    return inorderToBst(0,bst.size()-1,bst);
	
}
+2
sanketbhagat2 months ago
SIMPLE JAVA SOLUTION
 
1→ Tree using same nodes.
class GfG{
    
    void inorder(Node root, ArrayList<Node> list){
        if(root==null) return;
        inorder(root.left,list);
        list.add(root);
        inorder(root.right,list);
    }
    
    Node makeTree(ArrayList<Node> list, int l, int r){
        if(l>r) return null;
        int mid = l+(r-l)/2;
        Node root = list.get(mid);
        root.left = makeTree(list,l,mid-1);
        root.right = makeTree(list,mid+1,r);
        return root;
    }
    
    Node buildBalancedTree(Node root){
        //Add your code here.
        if(root==null) return root;
        ArrayList<Node> list = new ArrayList<>();
        inorder(root,list);
        return makeTree(list,0,list.size()-1);
    }
}
 
2→ Tree by creating new nodes.
class GfG{
    
    void inorder(Node root, ArrayList<Integer> list){
        if(root==null) return;
        inorder(root.left,list);
        list.add(root.data);
        inorder(root.right,list);
    }
    
    Node makeTree(ArrayList<Integer> list, int l, int r){
        if(l>r) return null;
        int mid = l+(r-l)/2;
        Node root = new Node(list.get(mid));
        root.left = makeTree(list,l,mid-1);
        root.right = makeTree(list,mid+1,r);
        return root;
    }
    
    Node buildBalancedTree(Node root){
        //Add your code here.
        if(root==null) return root;
        ArrayList<Integer> list = new ArrayList<>();
        inorder(root,list);
        return makeTree(list,0,list.size()-1);
    }
}
0
codecrackerp2 months ago
void inorder(Node*root,vector<int>&v){
   if(root==NULL)return;
   inorder(root->left,v);
   v.push_back(root->data);
   inorder(root->right,v);
}
Node*construct(int mid,int l,int r,vector<int>&v){
   if(l>r){
       return NULL;
   }
   mid=(l+r)/2;
   Node*newnode=new Node(v[mid]);
   newnode->left=construct(mid,l,mid-1,v);
   newnode->right=construct(mid,mid+1,r,v);
   return newnode;
}
Node* buildBalancedTree(Node* root)
{
 vector<int>v;
 inorder(root,v);
 int mid=-1,l=0,r=v.size()-1;
 Node*root1= construct(mid,l,r,v);
 return root1;
}
+1
aloksinghbais022 months ago
C++ solution having time complexity as O(N) and space complexity as O(N) is as follows :- 
 
Execution Time :- 0.0 / 1.1 sec
 
void inorder(Node *node,vector<int> &in){   if(!node) return;   inorder(node->left,in);   in.push_back(node->data);   inorder(node->right,in);}
Node* build(int s,int e,vector<int> &in){   if(s > e) return nullptr;      int mid = (s+e)/2;       Node *node = new Node(in[mid]);   node->left = node->right = nullptr;      node->left = build(s,mid-1,in);   node->right = build(mid+1,e,in);   return (node);}
Node* buildBalancedTree(Node* root){vector<int> in;inorder(root,in);return build(0,in.size()-1,in);} 
0
shiva10903 months ago
void inorder(Node* root , vector<int> &v){
    
    while(root){
        if(root->left == NULL){
            v.push_back(root->data);
            root = root->right;
        }
        else
        {
            Node* prev = root->left;
            
            while(prev->right != NULL && prev->right != root)
            {
                prev = prev->right;
            }
            
            if(prev->right == NULL){
                prev->right = root;
                root = root->left;
            }
            else{
                prev->right = NULL;
                v.push_back(root->data);
                root = root->right;
            }
        }
    }
}

Node* construct( vector<int> &v , int start , int end)
{
    if(start > end)
    {
        return NULL;
    }
    if(start == end)
    {
        Node* root = new Node(v[start]);
        return root;
    }
    int mid = (start+end)/2;
    Node* root = new Node(v[mid]);
    
    root->left = construct(v , start ,mid-1);
    root->right = construct(v, mid+1 , end);
    
    return root;
}
Node* buildBalancedTree(Node* root)
{
	// Code here
	vector<int> v;
	inorder(root , v);
	return construct(v,0,v.size()-1);
}
used morris traversal for reducing some space complexity , but spcae complexity is O(N) only... :'D
+5
arthurshelby3 months ago
void inorder(Node *root,vector<Node *>&v)

{
    if(root!=NULL)
    {
        inorder(root->left,v);
        v.push_back(root);
        inorder(root->right,v);
    }
}
Node *construct(vector<Node *>&v,int start,int end)
{
    if(start>end)
    return NULL;
    int mid=(start+end)/2;
    Node *temp=v[mid];
    temp->left=construct(v,start,mid-1);
    temp->right=construct(v,mid+1,end);
    return temp;
}
Node* buildBalancedTree(Node* root)
{
	// Code here
	vector<Node *>v;
	inorder(root,v);
	int start=0,end=v.size(); 
	return construct(v,start,end-1);
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.