#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct node
{
       int info;
       struct node* llink;
       struct node* rlink;
};
typedef struct node* NODE;

NODE insert(NODE root,int data)
{
     NODE temp,cur,prev;
     temp=(NODE)malloc(sizeof(struct node));
     if(temp==NULL) printf("\nOut of memory");
     temp->info=data;
     temp->rlink=temp->llink=NULL;
     if(root == NULL) 
     { 
     printf("\n1st time\n");
     root=temp;
     return root; 
     }
         prev=NULL;
         cur=root;
         while(cur != NULL)
         {
            prev=cur;
            if(cur->info == data)
            {
               printf("\ncannot insert duplicate data!\n");
               free(temp);
               return root;
            }
            if(data < cur->info)
               cur=cur->llink;
            else
               cur=cur->rlink;
         }
         if(data < prev->info)
           prev->llink=temp;
         else
           prev->rlink=temp;
     return root;
}

void preorder(NODE root)
{
     if(root == NULL) return;
     printf("\t%d",root->info);
     preorder(root->llink);
     preorder(root->rlink);
}
    
int main()
{
   NODE root=NULL;
   int choice,data;
   for(;;)
   {
   printf("\n   MENU\n");
   printf("\n1:insert\n2:display\nEnter your choice:");
   scanf("%d",&choice);
   switch(choice)
   {
      case 1:printf("\nEnter the data:");
             scanf("%d",&data);
             insert(root,data);   break;
      case 2:printf("\nPreorder traversal:\n");
             preorder(root); break;
      default:exit(0);
   }
   }
   getch();
   return 0;
}

the code is not creating the tree properly, even when i am inserting the second time it prints "1st time".Can anyone please tell me what is wrong??

Thanks in advance.

insert() returns a value, which you're ignoring.

insert() returns a value, which you're ignoring.

Thank you! its working! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.