Merge two BST 's | Practice | GeeksforGeeks

Given two BSTs, return elements of both BSTs in sorted form.

Example 1:
Input:
BST1:
       5
     /   \
    3     6
   / \
  2   4  
BST2:
        2
      /   \
     1     3
            \
             7
            /
           6
Output: 1 2 2 3 3 4 5 6 6 7
Explanation: 
After merging and sorting the
two BST we get 1 2 2 3 3 4 5 6 6 7.

Example 2:
Input:
BST1:
       12
     /   
    9
   / \    
  6   11
BST2:
      8
    /  \
   5    10
  /
 2
Output: 2 5 6 8 9 10 11 12
Explanation: 
After merging and sorting the
two BST we get 2 5 6 8 9 10 11 12.

Your Task:
You don't need to read input or print anything. Your task is to complete the function merge() which takes roots of both the BSTs as its input and returns an array of integers denoting the node values of both the BSTs in a sorted order.

Expected Time Complexity: O(M+N) where M and N are the sizes if the two BSTs.
Expected Auxiliary Space: O(Height of BST1 + Height of BST2).

Constraints:
1 ≤ Number of Nodes ≤ 105
0
subhanshukumar6314 days ago
 void inorder(Node* root,multiset<int> &st){       if(root==NULL) return;       inorder(root->left,st);       st.insert(root->data);       inorder(root->right,st);   }   vector<int> merge(Node *root1, Node *root2)   {      multiset<int> ans;      inorder(root1,ans);      inorder(root2,ans);      vector<int> res;      for(auto i:ans){          res.push_back(i);      }      return res;   }
+1
sarafraj019995 days ago
PYTHON EASY SOLUSION   <=> 
(h1+h2) space and (n1+n2) time complexity 
 
class Solution:
    def merge(self, root1, root2):
        
        def leftTravel(stak, root):
            if not root:
                return 
            stak.append(root)
            leftTravel(stak, root.left)

        res = []
        stak1, stak2 = [], []
        leftTravel(stak1, root1)
        leftTravel(stak2, root2)
        
        while stak1 and stak2:
            if stak1[-1].data < stak2[-1].data:
                temp = stak1.pop()
                res.append(temp.data)
                leftTravel(stak1, temp.right)
            
            elif stak2[-1].data < stak1[-1].data:
                temp = stak2.pop()
                res.append(temp.data)
                leftTravel(stak2, temp.right)
            
            else:
                temp1 = stak1.pop()
                temp2 = stak2.pop()
                res.append(temp1.data)
                res.append(temp2.data)
                leftTravel(stak1, temp1.right)
                leftTravel(stak2, temp2.right)
        
        while stak1:
            temp = stak1.pop()
            res.append(temp.data)
            leftTravel(stak1, temp.right)
        
        while stak2:
            temp = stak2.pop()
            res.append(temp.data)
            leftTravel(stak2, temp.right)
            
        return res
0
joyrockok1 week ago
class Solution{   PriorityQueue<Integer> queue;   //Function to return a list of integers denoting the node    //values of both the BST in a sorted order.   public List<Integer> merge(Node root1,Node root2)   {    queue = new PriorityQueue<Integer>();           // Write your code here    getMerge(root1, queue);         getMerge(root2, queue);        List<Integer> ansList = new ArrayList<Integer>();         while(queue.isEmpty() == false) {     ansList.add(queue.poll());    }        return ansList;   }      public void getMerge(Node node, PriorityQueue queue) {        if(node == null) return;        if(node.left == null) {     queue.add(node.data);    } else {     getMerge(node.left, queue);     queue.add(node.data);    }        if(node.right != null) {     getMerge(node.right, queue);    }       }} 
0
amarrajsmart1972 weeks ago
    void inorder(Node* root,vector<int> &v)   {       if(!root)       {           return ;       }       inorder(root->left,v);       v.push_back(root->data);       inorder(root->right,v);   }   vector<int> merge(Node *root1, Node *root2)   {      //Your code here      vector<int> v;      inorder(root1,v);      inorder(root2,v);      sort(v.begin(),v.end());      return v;   }
0
subhamk472 weeks ago
class Solution{   //Function to return a list of integers denoting the node    //values of both the BST in a sorted order.   public List<Integer> merge(Node root1,Node root2)   {       Queue<Integer> q1 = new LinkedList<>();       Queue<Integer> q2 = new LinkedList<>();       inOrder(root1,q1);       inOrder(root2,q2);       List<Integer> result = new ArrayList<Integer>();       while(!q1.isEmpty() || !q2.isEmpty()){           if(q1.peek()<q2.peek() ){               result.add(q1.poll());           }else{               result.add(q2.poll());           }           if(q1.isEmpty()) while(!q2.isEmpty()) result.add(q2.poll());           if(q2.isEmpty()) while(!q1.isEmpty()) result.add(q1.poll());       }       return result;   }   public void inOrder(Node root, Queue<Integer> q){       if(root==null) return;       inOrder(root.left,q);       q.offer(root.data);       inOrder(root.right,q);   }} 
0
amishasahu3282 weeks ago
TC→ O(n+m)
SC→ O(h1 +h2)
class Solution
{
    void BSTtoDLL(Node *root, Node* &head)
    {
    	if(!root) return;
    	BSTtoDLL(root->right, head);
    	root->right = head;
    	if(head != NULL)
    		head->left = root;
    	head = root;
    	BSTtoDLL(root->left, head);
    }
    
    Node *mergeSortedDLL(Node *head1, Node *head2)
    {
    	if(!head1) return head2;
    	if(!head2) return head1;
    	Node *head = NULL;
    	Node *tail = NULL;
    	
    	while(head1 != NULL && head2 != NULL)
    	{
    		if(head1->data < head2->data)
    		{
    			if(head == NULL)
    			{
    				head = tail = head1;
    				head1 = head1->right;
    			}
    			else
    			{
    				tail->right = head1;
    				head1->left = tail;
    				tail = head1;
    				head1 = head1->right;
    			}
    		}
    		else
    		{
    			if(head == NULL)
    			{
    				head = tail = head2;
    				head2 = head2->right;
    			}
    			else
    			{
    				tail->right = head2;
    				head2->left = tail;
    				tail = head2;
    				head2 = head2->right;
    			}
    		}
    	}
    	while(head1)
    	{
    		tail->right = head1;
    		head1->left = tail;
    		tail = head1;
    		head1 = head1->right;
    	}
    	while(head2)
    	{
    		tail->right = head2;
    		head2->left = tail;
    		tail = head2;
    		head2 = head2->right;
    	}
    	
    	return head;
    }
    int countNodes(Node *&head)
    {
    	int count = 0;
    	Node *curr = head;
    	while(curr)
    	{
    		count++;
    		curr = curr->right;
    	}
    	return count;
    }
    vector<int> DLLtoInorder(Node *&head)
    {
        vector<int> inorder;
        if(!head) return inorder;
        while(head)
        {
            inorder.push_back(head->data);
            head = head->right;
        }
        return inorder;
    }
    public:
    //Function to return a list of integers denoting the node 
    //values of both the BST in a sorted order.
    vector<int> merge(Node *root1, Node *root2)
    {
       // Step1: convert BST to DLL
    	Node * head1 = NULL, *head2 = NULL;
    	BSTtoDLL(root1, head1);
    	head1->left = NULL;
    	BSTtoDLL(root2, head2);
    	head2->left = NULL;
    	
    	// Step2: merge two DLL
    	Node *mergedDLL = mergeSortedDLL(head1, head2);
    	
    	// Step3: convert sorted DLL to vector
    	return DLLtoInorder(mergedDLL);
    }
};
0
amishasahu328
This comment was deleted.
-1
tanashah3 weeks ago
0
chhitizgoyal3 weeks ago
Java Solution.
 void inorder1(Node root1, ArrayList<Integer> list){       if(root1!=null){           inorder1(root1.left, list);           list.add(root1.data);           inorder1(root1.right, list);       }   }   void inorder2(Node root2, ArrayList<Integer> list){       if(root2!=null){           inorder2(root2.left, list);           list.add(root2.data);           inorder2(root2.right, list);       }   }   public List<Integer> merge(Node root1,Node root2)   {       ArrayList<Integer> list = new ArrayList<Integer>();       if(root1==null && root2==null){           return list;       }       inorder1(root1, list);       inorder2(root2, list);       Collections.sort(list);       return list;   }
0
jaydhurat3 weeks ago
class Solution
{
   //Function to return a list of integers denoting the node 
   //values of both the BST in a sorted order.
   public List<Integer> merge(Node root1,Node root2)
   {
       List<Integer> a = new ArrayList<>();
       check1(root1,a);
       check2(root2,a);
       Collections.sort(a);
       return a;
   }
   public void check1(Node root,List<Integer> a)
   {
       if(root==null)
       {
           return;
       }
       check1(root.left,a);
       if(root!=null){
       a.add(root.data);
       }
       check1(root.right,a);
   }
   public void check2(Node root,List<Integer> a)
   {
        if(root==null)
       {
           return;
       }
       check2(root.left,a);
       if(root!=null){
       a.add(root.data);
       }
       check2(root.right,a);
   }
}

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.