Rakesh_Kumar
Rakesh_Kumar

Reputation: 1442

Inorder traversal is printing in wrong order

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<string.h>
struct node{
 char *name;
 struct node *lchild;
 struct node *rchild;
};
void find(char *str,struct node **root,struct node **loc,struct node **par)
{
struct node *ptr,*ptrsave;
*loc=NULL;
*par=NULL;
if(*root==NULL)
{
   return;
}
if(!strcmp((*root)->name,str))
{
     *loc=*root;
     return;
}
ptrsave=NULL;
ptr=*root;
while(ptr!=NULL)
{
   if(!strcmp(ptr->name,str)) break;
   ptrsave=ptr;
   if(strcmp(ptr->name,str)>0)
      ptr=ptr->lchild;
   else
      ptr=ptr->rchild;
}
*loc=ptr;
*par=ptrsave;
}
void insert(struct node **p,char *str)
{
struct node *location,*parent,*temp;
find(str,&(*p),&location,&parent);
if(location!=NULL)
{
       printf("Element already exists\n");
       return;
}
temp=(struct node *)malloc(sizeof(struct node));
temp->name=strdup(str);
temp->lchild=NULL;
temp->rchild=NULL;
if(parent==NULL)
{
        *p=temp;
        return;
}
else
{
     if(strcmp(parent->name,str)>0)
        parent->lchild=temp;
     else
        parent->rchild=temp;
}
}


void inorder(struct node *root)
{
if(root!=NULL)
{
   preorder(root->lchild);
   printf("[%30s]\n",root->name);
   preorder(root->rchild);
}
}
int main()
{
struct node *root=NULL;
insert(&root,"Crocin");
insert(&root,"Acetyl");
insert(&root,"Colchichine");
insert(&root,"Diclofenac_50mg");
insert(&root,"Diclofenac_25mg");
insert(&root,"Morphine Sulphate");
insert(&root,"Fentanyl");
insert(&root,"Dolo");
insert(&root,"Ibuprofen");
insert(&root,"Tramadol");
insert(&root,"Paracetamol");
inorder(root);
getchar();
return 0;
}

This is the code i am using for creating and inserting nodes in a binary search tree. After that i created recursive inorder function. but this is not giving the right ouput. I am not able to find error that is creating discrepancy. Can someone suggest where i am going wrong?

Upvotes: 1

Views: 86

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

Change

void inorder(struct node *root)
{
if(root!=NULL)
{
   preorder(root->lchild);
   printf("[%30s]\n",root->name);
   preorder(root->rchild);
}

to

void inorder(struct node *root)
{
if(root!=NULL)
{
   inorder(root->lchild);
   printf("[%30s]\n",root->name);
   inorder(root->rchild);
}

You are using another function (preorder) (not listed in your code)

Upvotes: 1

Related Questions