Friday 14 November 2014

Inorder traversal without recursion using single threaded binary tree

#include<stdio.h>
struct node//defining node of tree
{
int data;
struct node *l,*r,*rt;
};
typedef struct node node;
getnode()
{
return ((node *)malloc(sizeof(node)));
}
insert(int val,node *root)//function to insert node after root
{
node *p=getnode();
p->data=val;
p->l=NULL;
p->r=NULL;
p->rt=NULL;
if(val<root->data&&root->l!=NULL)
{
insert(val,root->l);
}
if(val>=root->data&&root->r!=NULL)
{
insert(val,root->r);
}
if(val>=root->data&&root->r==NULL)
{
root->r=p;
}
if(val<root->data&&root->l==NULL)
{
root->l=p;
}
}
int i=0;
leftmost(node *n)//function to go to leftmost node of the given node
{
    if(n==NULL){return NULL;}
    while(n->l!=NULL)
        n=n->l;
    return n;
}
int la=0;
inorderst(node *root,int a[])//function to store the inorder traversal in array
{
if(root!=NULL)
{
    inorderst(root->l,a);
printf("%d\n",a[la]=root->data);
    la++;
    inorderst(root->r,a);
}
}
search(node *root,int key)//function to search node
{
if(root->data==key){return root;}
if(root->data<key){return search(root->r,key);}
if(root->data>key){return search(root->l,key);}
}
main()
{
int k;
printf("Enter the total number of nodes you want to enter");
scanf("%d",&k);
int a[k];
int ir;
for(ir=0;ir<k;ir++)
{
    printf("\nEnter %d element",ir+1);
    scanf("%d",&a[ir]);
}
node *root=getnode();
root->data=a[0];
root->l=NULL;
root->r=NULL;
root->rt=NULL;
node *p=root;
for(ir=1;ir<k;ir++)
{
insert(a[ir],root);
root=p;
}
root=p;
int y[k];
root=p;
printf("Inorder traversal with recursion\n");
inorderst(root,y);
root=p;
int u;
for(ir=0;ir<k;ir++)//making rthread connections
{
node *pa;
pa=search(root,a[ir]);
if(pa->r==NULL)
{
for(u=0;u<k-1;u++)
{
    if(y[u]==pa->data)
    {
       root=p;
        node *ra=search(root,y[u+1]);
    pa->rt=ra;
    break;
    }
}
}
}
printf("Inorder using rthread without recursion\n");
root=p;
node *cur=leftmost(root);
while(cur!=NULL)
{
    printf("%d\n",cur->data);
    if(cur->rt!=NULL)
    {
        cur=cur->rt;
    }
    else
    {
        cur=leftmost(cur->r);
    }
}
}

No comments:

Post a Comment