Create in-order threaded binary tree and perform traversals

, by Prashant Gunjal


/*
3. Create in-order threaded binary tree and perform traversals
*/
#include<conio.h>
#include<iostream.h>

class node
{
public:
int lf,rf,data;
node *lc,*rc;
node()
{
lc=rc=NULL;
lf=rf=0;
}
};

class tbt
{
private:
node*root,*header;
public:
tbt()
{
root=header=NULL;
}
void create();
void inorder();
void preorder();
void postorder();
node * getnode();
};

void tbt::create()
{
header=new node;
int no;
node * temp=NULL;
cout<<"\nEnter no of nodes =>";
cin>>no;
for(int i=0;i<no;i++)
{
temp=new node;
cout<<"\nEnter data=> ";
cin>>temp->data;
if(root==NULL)
{
root=temp;
root->lc=root->rc=header;
root->lf=root->rf=1;
}
else
{
node * last=root;
while(1)
{
if(last->data>temp->data)
{
if(last->lf==1)
{
temp->lf=last->lf;
last->lf=0;
last->lc=temp;
temp->lc=header;
temp->rc=last;
temp->rf=1;
break;
}
else
last=last->lc;
}
else
{
if(last->data<temp->data)
{
if(last->rf==1)
{
temp->rf=last->rf;
last->rf=0;
last->rc=temp;
temp->rc=header;
temp->lc=last;
temp->lf=1;
break;
}
else
last=last->rc;
}
else
{
cout<<"\nDuplicate node "<<temp->data;
break;
}
}
}
}
}
}
void tbt::preorder()
{
if(root==NULL)
{
cout<<"\nEmpty tree";
}
else
{
cout<<"\nPreorder => ";
node*temp=root;
while(temp!=header)
{
while(temp->lf!=1)
{
cout<<"\t"<<temp->data;
temp=temp->lc;
}
cout<<"\t"<<temp->data;
while(temp->rf==1&&temp->rc!=header)
{
temp=temp->rc;
}
temp=temp->rc;
}
}
}
void tbt::inorder()
{
int flag=0;
if(root==NULL)
{
cout<<"\nEmpty tree";
}
else
{
node * pt=root;
cout<<"\nInorder=> ";
while(pt!=header)
{
while(pt->lf==0&&flag==0)
{
pt=pt->lc;
}
cout<<"\t"<<pt->data;
if(pt->rf==0)
{
pt=pt->rc;
flag=0;
}
else
{
pt=pt->rc;
flag=1;
}

}
}
}
void tbt::postorder()
{
int q[20],i=0;
if(root==NULL)
cout<<"\nEmpte tree ";
else
{
node*pt=root;
cout<<"\nPostorder=> ";
while(pt!=header)
{
while(pt->rf==0)
{
q[i++]=pt->data;
pt=pt->rc;
}
q[i++]=pt->data;

while(pt->lf==1&&pt->lc!=header)
{
pt=pt->lc;
}
pt=pt->lc;
}
i--;
for(i;i>=0;i--)
cout<<"\t"<<q[i];

}
}
void main()
{
clrscr();
tbt obj;
obj.create();
obj.preorder();
obj.inorder();
obj.postorder();
getch();
}
/*
OUTPUT

Enter no of nodes =>5

Enter data=> 10

Enter data=> 5

Enter data=> 2

Enter data=> 23

Enter data=> 45

Preorder =>     10      5       2       23      45
Inorder=>       2       5       10      23      45
Postorder=>     2       5       45      23      10
*/

0 comments: