TERNORY SEARCH TREE
having two data field and three pointers to the childs.
#include<iostream>
using namespace std;
struct tnode
{
int data1,data2;
tnode *left,*right,*mid;
};
void add(tnode *&t,int k1,int k2)
{
if(t==NULL)
{
t=new tnode;
t->data1=k1;
t->data2=k2;
t->right=NULL;
t->left=NULL;
t->mid=NULL;
}
else
{
if(k1<t->data1)
add(t->left,k1,k2);
if(k1>t->data2)
add(t->right,k1,k2);
else
add(t->mid,k1,k2);
}}
void search(tnode *t,int k)
{
if(t->data1==k||t->data2==k)
cout<<"found";
else
{
if(k<t->data1)
search(t->left,k);
else if(k>t->data2)
search(t->right,k);
else if(k>t->data1&&k<t->data2)
search(t->mid,k);
}
}
void output(tnode *t)
{
if(t!=NULL)
{
cout<<t->data1<<" "<<t->data2<<" ";
output(t->left);
output(t->mid);
output(t->right);
}
}
int main()
{
tnode *t;
t=new tnode;
t=NULL;
cout<<"enter the key values";
int k1,k2;
cin>>k1>>k2;
do
{
add(t,k1,k2);
cin>>k1>>k2;
}while(k1!=-1&&k2!=-1);
output(t);
cout<<"\nenter the element to be searched";
int a;
cin>>a;
search(t,a);
return 0;
}
having two data field and three pointers to the childs.
#include<iostream>
using namespace std;
struct tnode
{
int data1,data2;
tnode *left,*right,*mid;
};
void add(tnode *&t,int k1,int k2)
{
if(t==NULL)
{
t=new tnode;
t->data1=k1;
t->data2=k2;
t->right=NULL;
t->left=NULL;
t->mid=NULL;
}
else
{
if(k1<t->data1)
add(t->left,k1,k2);
if(k1>t->data2)
add(t->right,k1,k2);
else
add(t->mid,k1,k2);
}}
void search(tnode *t,int k)
{
if(t->data1==k||t->data2==k)
cout<<"found";
else
{
if(k<t->data1)
search(t->left,k);
else if(k>t->data2)
search(t->right,k);
else if(k>t->data1&&k<t->data2)
search(t->mid,k);
}
}
void output(tnode *t)
{
if(t!=NULL)
{
cout<<t->data1<<" "<<t->data2<<" ";
output(t->left);
output(t->mid);
output(t->right);
}
}
int main()
{
tnode *t;
t=new tnode;
t=NULL;
cout<<"enter the key values";
int k1,k2;
cin>>k1>>k2;
do
{
add(t,k1,k2);
cin>>k1>>k2;
}while(k1!=-1&&k2!=-1);
output(t);
cout<<"\nenter the element to be searched";
int a;
cin>>a;
search(t,a);
return 0;
}
No comments:
Post a Comment