Print Common Nodes in Two Binary Search Trees ( intersection of two BSTs )

PROBLEM :

Given two Binary Search Trees, find common nodes in them. In other words, find intersection of two BSTs.

Example:




--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------


/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;                                 */

int size_tree(tree* root) ;
void inorder_array_fill(tree* ,int [],int *) ;

void check_intersection_2BST(tree *root1,tree *root2)
{
int s1,s2 ;
s1=size_tree(root1) ;
s2=size_tree(root2) ;

int array1[s1],array2[s2],i ;
i=0 ;
inorder_array_fill(root1,array1,&i) ;
i=0 ;
inorder_array_fill(root2,array2,&i) ;

int a,b ;
a=0;
b=0 ;

while(a!=s1&&b!=s2)
{
if(array1[a]==array2[b])
{
cout<<array1[a]<<" " ;
a++ ;
b++ ;
}
else if(array1[a]>array2[b])
b++ ;
else
a++ ;
}
}

int size_tree(tree* root)
{
if(root==NULL)
return 0 ;

return ((size_tree(root->left))+(size_tree(root->right))+1) ;
}

void inorder_array_fill(tree* root,int a[],int *s)
{
    if(root==NULL)
        return  ;
     
    inorder_array_fill(root->left,a,&(*s)) ;
    a[(*s)++]=root->info ;
    inorder_array_fill(root->right,a,&(*s)) ;
 
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )