#include<stdio.h>
#include<stdlib.h>
struct tree
{
    int info;
    struct tree * left;
    struct tree *right;
};
struct tree *root=NULL;
struct tree * insert(struct tree *root,int item);
void display(struct tree *root);
int main()
{
    int a,b,c,item;
    do
    {
        printf("press 1 to enter an element,2 to display,3 to quit\n");
        scanf("%d",&a);
        if(a==1)
        {
            printf("enter the item to be inserted\n");
            scanf("%d",&item);
            root=insert(root,item);
        }
        if(a==2)
        display(root);

    } while(a!=3);
    return 0;
}
struct tree * insert(struct tree *root,int item)
{
    struct tree *par,*u,*ptr;
    ptr=root;
    par=NULL;
    u=(struct tree *)malloc(sizeof(struct tree));
    u->info=item;
    u->left=NULL;
    u->right=NULL;

    if(root==NULL)
    {
        root=u;
        return root;

    }
    while(ptr!=NULL)
    {
        par=ptr;
        if((ptr->info)<item)
        {
            ptr=ptr->right;
        }
        if((ptr->info)>item)
        {
            ptr=ptr->left;
        }
    }
    if(item>(par->info))
    {
        par->right=u;
    }
    else
    {
        par->left=u;
    }
return root;
}
void display(struct tree *root)
{
    if(root==NULL)
    return;
    //printf("inorder traversal is\n");
    display(root->left);
    printf("%d\t",root->info);
    display(root->right);
}

Recommended Answers

All 4 Replies

Line 54 should be an else if.

thanks for the reply.But why only 'if' wont work here?

Let's use a simple example of a tree with only one node. If the new node you're adding is to be added to the right subtree, the first if will set ptr to NULL. Then the second if will test ptr->info, which is dereferencing a null pointer:

The reason you need an else if is because you're moving either left or right, not potentially both. You could check ptr to see if it's NULL in the second if, but that's unnecessary extra work.

Got it.Thanks a lot!!

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.