Binary Tree to BST | Practice | GeeksforGeeks

Given a Binary Tree, convert it to Binary Search Tree in such a way that keeps the original structure of Binary Tree intact.
 
Example 1:
Input:
      1
    /   \
   2     3
Output: 1 2 3


Example 2:
Input:
          1
       /    \
     2       3
   /        
 4       
Output: 1 2 3 4
Explanation:
The converted BST will be

        3
      /   \
    2     4
  /
 1

 
Your Task:
You don't need to read input or print anything. Your task is to complete the function binaryTreeToBST() which takes the root of the Binary tree as input and returns the root of the BST. The driver code will print inorder traversal of the converted BST.

Expected Time Complexity: O(NLogN).
Expected Auxiliary Space: O(N).

Constraints:
1 <= Number of nodes <= 1000
-1
sikkusaurav1236 days ago
class Solution{ public:   // The given root is the root of the Binary Tree   // Return the root of the generated BST   void solve(Node* root,vector<int>&v)   {       if(root!=NULL)       {           solve(root->left,v);           v.push_back(root->data);           solve(root->right,v);       }   }   void solve2(Node* root,vector<int>&v,int &i)   {       if(root!=NULL)       {           solve2(root->left,v,i);           root->data=v[i];           i++;           solve2(root->right,v,i);       }   }      Node *binaryTreeToBST (Node *root)   {       //Your code goes here       vector<int>v;       int i=0;       solve(root,v);       sort(v.begin(),v.end());       solve2(root,v,i);       return root;   }};
0
amarrajsmart1972 weeks ago
 void inorderTree(Node *root,vector<int> &v)   {       if(!root)       {           return ;       }       inorderTree(root->left,v);       v.push_back(root->data);       inorderTree(root->right,v);   }      void inorderBST(Node* root,vector<int>&v,int &i)   {       if(!root)       {           return ;       }       inorderBST(root->left,v,i);       root->data=v[i++];       inorderBST(root->right,v,i);   }      Node *binaryTreeToBST (Node *root)   {       //Your code goes here       vector<int> v;       int i=0;       if(!root)       return NULL;       inorderTree(root,v);       sort(v.begin(),v.end());       inorderBST(root,v,i);       return root;   }
+1
jaatgfg111 month ago
very ezz soln 
 
class Solution{ public:   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* inorderbst(Node *root1,vector<int>v,int s,int e){       if(s>e){           return NULL;       }       int mid=(s+e)/2;       root1=new Node(v[mid]);       root1->left=inorderbst(root1->left,v,s,mid-1);       root1->right=inorderbst(root1->right,v,mid+1,e);       return root1;          }   Node *binaryTreeToBST (Node *root)   {        vector<int>v;       inorder(root,v);       sort(v.begin(),v.end());       Node* root1=NULL;       int s=0;       int e=v.size()-1;       return inorderbst(root1,v,s,e);                 }};
+2
sfazal0001 month ago
void inorder_tree(node* root,vector<int> &v){   if(root == NULL)   {       return;   }      inorder_tree(root->left,v);   v.push_back(root->data);   inorder_tree(root->right,v);}
 
void inorder_BST(node* root , vector<int > &v,int &i){   if(root == NULL)   {       return ;   }      inorder_BST(root->left , v , i);      root->data = v[i];   i++;      inorder_BST(root->right, v, i);}              
 
node* BTtoBST(node* root){   if(root == NULL)   {       return NULL;   }      vector<int> v;   inorder_tree(root,v);      sort(v.begin(),v.end());      int i=0;      inorder_BST(root,v,i);      return root;}   
0
detroix072 months ago
Node* solve(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=solve(InOrder,n,InOrderStart,mid-1);   root->right=solve(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 *binaryTreeToBST (Node *root)   {       vector<int> InOrder;       InOrderTraversal(root,InOrder);       sort(InOrder.begin(),InOrder.end());       int n = InOrder.size();       Node* ans = solve(InOrder,n,0,n-1);       return ans;   }
+1
sfazal0002 months ago
void   inorder_Tree(node* root , vector<int> &v){   if(root == NULL)   {       return ;   }      inorder_Tree(root->left,v);      v.push_back(root->data);      inorder_Tree(root->right,v);     }   
void  inorder_BST(node* root , vector<int> &v, int &i){   if(root == NULL)   {       return ;   }      inorder_BST(root->left,v,i);      root->data = v[i];   i++;      inorder_BST(root->right,v,i);      return ;}   
 
node* binaryTreeToBST(node* root){   vector<int > v;   if(root == NULL)   {       return root;   }      inorder_Tree(root,v);      sort(v.begin(),v.end());      int i=0;   inorder_BST(root,v,i);      return root;}
 
+1
golaravi5552 months ago
int i=0;   void solve(Node* root,vector<int>&v){       if(!root)return;       solve(root->left,v);       root->data=v[i++];       solve(root->right,v);   }   void inorder(Node *root,vector<int>&v){       if(!root)return;       inorder(root->left,v);       v.push_back(root->data);       inorder(root->right,v);   }   Node *binaryTreeToBST (Node *root)   {       //Your code goes here       vector<int>v;       inorder(root,v);       sort(v.begin(),v.end());       solve(root,v);       return root;                 }
0
sanketbhagat2 months ago
SIMPLE JAVA SOLUTION
class Solution{
    
    int idx;
    
    void inorder(Node root, ArrayList<Integer> list, boolean write){
        if(root==null) return;
        inorder(root.left,list,write);
        if(write) root.data = list.get(idx++);
        else list.add(root.data);
        inorder(root.right,list,write);
    }
    
    // The given root is the root of the Binary Tree
    // Return the root of the generated BST
    Node binaryTreeToBST(Node root){
       // Your code here
       ArrayList<Integer> list = new ArrayList<>();
       inorder(root,list,false);
       Collections.sort(list);
       idx = 0;
       inorder(root,list,true);
       return root;
    }
}
-1
hamidnourashraf2 months ago
class Solution:
    # The given root is the root of the Binary Tree
    # Return the root of the generated BST
    def _inorder(self, root, res, res_val):
        if root is None:
            return 
        self._inorder(root.left, res, res_val)
        res.append(root)
        res_val.append(root.data)
        self._inorder(root.right, res, res_val)
    def binaryTreeToBST(self, root):
        res = []
        res_val = []
        self._inorder(root, res, res_val)
        res_val = sorted(res_val)
        for i in range(len(res)):
            res[i].data = res_val[i]
        return root
0
guruprasadnb14022 months ago
void inorder(Node *root,vector<int>&ans){       if(root==NULL)return;       inorder(root->left,ans);       ans.push_back(root->data);       inorder(root->right,ans);   }   void solve(Node *root,vector<int>ans,int &i){       if(i>=ans.size()||root==NULL)return;       solve(root->left,ans,i);       root->data=ans[i++];       solve(root->right,ans,i);   }   Node *binaryTreeToBST (Node *root)   {       //Your code goes here       vector<int>ans;       inorder(root,ans);       int i=0;       sort(ans.begin(),ans.end());       solve(root,ans,i);       return root;   }
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.