Showing posts with label print common nodes in BST. Show all posts
Showing posts with label print common nodes in BST. Show all posts

Sunday, October 18, 2015

print common nodes in BST

#include <iostream>
using namespace std;
struct node
{
int data;
node *left,*right;
};
void print(node *t)
{
if(t!=NULL)
{
cout<<t->data<<" ";
print(t->left);
print(t->right);
}
}
node *newnode(int a)
{
node *t=new node;
t->data=a;
t->left=t->right=NULL;
return t;
}
void create(node *&t,int a)
{
if(t==NULL)
{
t=new node;
t->data=a;
t->left=NULL;
t->right=NULL;

}
else
{
if(a<t->data)
create(t->left,a);
else
create(t->right,a);
}
}
void printcommon(node *t1,node *t2)
{
if(t1==NULL||t2==NULL)
return ;

if(t1&&t2&&t1->data==t2->data)
cout<<t1->data<<" ";
else if(t1->data>t2->data)
{
printcommon(t1,t2->right);
printcommon(t1->left,t2);
}
else if(t1->data<t2->data){
printcommon(t1->right,t2);
printcommon(t1,t2->left);
}

}
int main()
{
node *t=NULL,*p=NULL;
int a[]={34,12,35,2,46,8,23,95,24};
int b[]={4,12,5,2,46,8,23,9,24};
int n=sizeof(a)/sizeof(a[0]);
cout<<n<<" \n";
int i=0;

for(int i=0;i<n;i++)
{
create(t,a[i]);
create(p,b[i]);
}

printcommon(t,p);

}

Contributors

Translate