Find Common Nodes in two BSTs | Practice | GeeksforGeeks

Given two Binary Search Trees. Find the nodes that are common in both of them, ie- find the intersection of the two BSTs.
Example 1:
Input:
BST1:
                  5
               /     \
             1        10
           /   \      /
          0     4    7
                      \
                       9
BST2:
                10 
              /    \
             7     20
           /   \ 
          4     9
Output: 4 7 9 10


Example 2:
Input:
BST1:
     10
    /  \
   2   11
  /  \
 1   3
BST2:
       2
     /  \
    1    3
Output: 1 2 3

Your Task:
You don't need to read input or print anything. Your task is to complete the function findCommon() that takes roots of the two BSTs as input parameters and returns a list of integers containing the common nodes in sorted order. 
Expected Time Complexity: O(N1 + N2) where N1 and N2 are the sizes of the 2 BSTs.
Expected Auxiliary Space: O(H1 + H2) where H1 and H2 are the heights of the 2 BSTs.
Constraints:
1 <= Number of Nodes <= 105
0
singhdipranjan674 days ago
class Solution
{
    //Function to find the nodes that are common in both BST.
	public static ArrayList<Integer> findCommon(Node root1,Node root2)
    {
        ArrayList<Integer> list=new ArrayList<>();
        HashSet<Integer> set=new HashSet<>();
        Queue<Node> q=new LinkedList<>();
        q.add(root1);
        while(!q.isEmpty())
        {
            Node curr=q.poll();
            set.add(curr.data);
            if(curr.left!=null)
            q.add(curr.left);
            if(curr.right!=null)
            q.add(curr.right);
        }
        q.add(root2);
        while(!q.isEmpty())
        {
            Node curr=q.poll();
            if(set.contains(curr.data))
            list.add(curr.data);
            if(curr.left!=null)
            q.add(curr.left);
            if(curr.right!=null)
            q.add(curr.right);
        }
    
         Collections.sort(list);
         return list;
        
    }
}
0
rajkirangupta994 days ago
class Solution{   //Function to find the nodes that are common in both BST.    static void in(Node root,HashSet<Integer>h)   {       if(root==null)       return;       in(root.left,h);       h.add(root.data);       in(root.right,h);   }  static void in1(Node root,HashSet<Integer>h,ArrayList<Integer>a)   {       if(root==null)       return ;       in1(root.left,h,a);       if(h.contains(root.data))           a.add(root.data);       in1(root.right,h,a);       }public static ArrayList<Integer> findCommon(Node root1,Node root2)   {       HashSet<Integer>h=new HashSet<Integer>();       in(root1,h);       ArrayList<Integer>a=new ArrayList<Integer>();       in1(root2,h,a);       return a;                 }}
0
sadiiqyare662 weeks ago
class Solution
{
    //Function to find the nodes that are common in both BST.
	public static ArrayList<Integer> findCommon(Node root1,Node root2)
    {
        //code here
        ArrayList<Integer> arr = new ArrayList<>();
        fun2(root1,root2,arr);
        return arr;
        
    }
    
    static void fun2(Node root1,Node root2, ArrayList<Integer> arr){
        if(root1 == null){
            return;
        }
        fun2(root1.left,root2,arr);
        if(fun(root2,root1.data) == true){
            arr.add(root1.data);
        }
        
        fun2(root1.right,root2,arr);
    }
    
    static boolean fun(Node root, int x){
        
        if(root == null){
            return false;
        }
        
        if(root.data == x){
            return true;
        }
        else if(root.data > x){
            return fun(root.left, x);
        }
        else{
            return fun(root.right,x);
        }
        
    }
}
0
nishant782 weeks ago
Using unordered_map.
Run time => .44sec

void insert(Node *root,unordered_map<int,int>&m){
    if(root==NULL){
        return;
    }
    insert(root->left,m);
    m[root->data]++;
    insert(root->right,m);
    
}
    vector <int> findCommon(Node *root1, Node *root2)
    {
     //Your code here
     unordered_map<int,int>m;
     
     insert(root1,m);
     insert(root2,m);
     vector<int>v;
     for(auto it:m){
         if(it.second>1){
             v.push_back(it.first);
         }
     }
     sort(v.begin(),v.end());
     return v;
    }
};
0
arbaazmakandar982 weeks ago
void getInorder(Node* root, vector<int> &res){       if(!root) return;       getInorder(root->left, res);       res.push_back(root->data);       getInorder(root->right, res);       return;   }   vector <int> findCommon(Node *root1, Node *root2)   {    //Your code here    vector <int> inorder1;    getInorder(root1, inorder1);    vector <int> inorder2;    getInorder(root2, inorder2);        vector<int> res ;     int i1 = 0;    int i2 = 0;    while(!inorder1.empty() && !inorder2.empty()){        if(inorder1.front() == inorder2.front()){            res.push_back(inorder1.front());            inorder1.erase(inorder1.begin());            inorder2.erase(inorder2.begin());        }        else if(inorder1.front() < inorder2.front()){           //  res.push_back(inorder1.front());            inorder1.erase(inorder1.begin());           //  inorder2.pop_front();        }        else if(inorder1.front() > inorder2.front()){           //  res.push_back(inorder1.front());            inorder2.erase(inorder2.begin());           //  inorder2.pop_front();        }    }    return res;       }
0
mandwalyash11
This comment was deleted.
0
vijaypratapchauhan222 months ago
Why it is not giving any output while using unordered_map, but it is working using unordered_set;
here is the code using unordered_map...
 
 void solve(Node* root,vector<int> &ans,unordered_map<Node* ,bool> &visited){       if(root==NULL)          return ;                 solve(root->left,ans,visited);       if(visited[root]==true)             ans.push_back(root->data);       solve(root->right,ans,visited);      }   void markVisited(Node* root,unordered_map<Node*,bool> &visited){       if(root==NULL)          return;          markVisited(root->left,visited);       visited[root]=true;       markVisited(root->right,visited);    }   //Function to find the nodes that are common in both BST.    vector <int> findCommon(Node *root1, Node *root2)   {        vector<int>ans;      unordered_map<Node*,bool>visited;      markVisited(root1,visited);      solve(root2,ans,visited);      return ans;         }
0
007msr0072 months ago
C++ Solution using Iterative Inorder traversal
Time Complexity : O(n1+n2)
Aux Space : O(h1+h2)
 
                **************CODE****************
vector <int> findCommon(Node *root1, Node *root2)
    {
     //Your code here
     vector<int>result ;
     stack<Node*>s1;
     stack<Node*>s2;
        while(root1!=NULL)
         {
             s1.push(root1);
             root1 = root1->left;
         }
         while(root2!=NULL)
         {
             s2.push(root2);
             root2 = root2->left;
         }
     while(!s1.empty() && !s2.empty())
     {
         if(s1.top()->data<s2.top()->data)
         {
             root1 = s1.top()->right;
             s1.pop();
         }
         else if(s1.top()->data>s2.top()->data)
         {
             root2 = s2.top()->right;
             s2.pop();
         }
         else
         {
             result.push_back(s1.top()->data);
             
              root1 = s1.top()->right;
              s1.pop();
              root2 = s2.top()->right;
              s2.pop();
              
         }
         while(root1!=NULL)
         {
             s1.push(root1);
             root1 = root1->left;
         }
         while(root2!=NULL)
         {
             s2.push(root2);
             root2 = root2->left;
         }
     }
    return result;
    }
 
+1
krishnarathi3412 months ago
C++ Approach in one array
Use Iterative Inorder traversal
vector <int> findCommon(Node *root1, Node *root2)
    {
     //Your code here
        vector<int> ans;
        stack<Node *> st1,st2;
        Node *curr1 = root1;
        Node *curr2 = root2;
        while((!st1.empty() || curr1!=NULL) && (!st2.empty() || curr2!=NULL)){
            
            while(curr1!=NULL){
                st1.push(curr1);
                curr1 = curr1->left;
            }
            
            while(curr2!=NULL){
                st2.push(curr2);
                curr2 = curr2->left;
            }
            
            Node *t1 = st1.top();
            Node *t2 = st2.top();
            
            if(t1->data < t2->data){
                st1.pop();
                curr1 = t1->right;
            }
            else if(t1->data > t2->data){
                st2.pop();
                curr2 = t2->right;
            }
            else{
                ans.push_back(t1->data);
                st1.pop();
                curr1 = t1->right;
                st2.pop();
                curr2 = t2->right;
            }
            
        }
        return ans;
    }
0
vishalpandey100220002 months ago
class Solution{   //Function to find the nodes that are common in both BST.public static ArrayList<Integer> findCommon(Node root1,Node root2)   {       //code here        ArrayList<Integer>arr=new ArrayList<>();       ArrayList<Integer>arr1=new ArrayList<>();       ArrayList<Integer>arr2=new ArrayList<>();       if (root1==null || root2==null){           return arr;       }       Ino(root1,arr1);       Ino(root2,arr2);       for (int i=0;i< arr2.size();i++){           if (arr1.contains(arr2.get(i))){               arr.add(arr2.get(i));           }       }       return arr;   }   private static void Ino(Node root1, ArrayList<Integer> arr1) {       if (root1==null){           return;       }       if (root1!=null){           Ino(root1.left,arr1);           arr1.add(root1.data);           Ino(root1.right,arr1);       }   }} 
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.