0

I am trying to insert node into a binary search tree inserting a node in the left subtree is giving no issues but inserting a node at right subtree is giving issue of null pointer exception.

inserting a node first time work properly but when I try to insert a new node in the right part of the root, I found the root has already been given some garbage value while traversing n it prints null pointer exception.

typedef struct tree
{
    int elt;
    struct tree *left,*right;
}T;
    T *RT=null;

void insert()
{
    int n;
    T *move,*temp,*back;
    printf("\nEnter an element: ");
    scanf("%d",&n);
    temp=(T *)malloc(sizeof(T *));
    temp->left=NULL;
    temp->right=NULL;
    temp->elt=n;
    if(RT==NULL)
        RT=temp;
    else
    {
        move=RT;
        while(move!=NULL)
        {
            back=move;
            if(move->elt>=n)
                move=move->left;
            else if(move->elt<n)
                move=move->right;
        }
        if(back->elt>=n)
            back->left=temp;
        else
            back->right=temp;
    }
    printf("%d %d %d",RT->elt,RT->left->elt,RT->right->elt);
}
Vaibhav
  • 15
  • 2
  • 1
    `malloc(sizeof (T))`, not `sizeof(T *)` – npostavs Apr 10 '15 at 20:42
  • possible duplicate of [Are "malloc(sizeof(struct a \*))" and "malloc(sizeof(struct a))" the same?](http://stackoverflow.com/questions/8762278/are-mallocsizeofstruct-a-and-mallocsizeofstruct-a-the-same), or maybe [what's the correct way to malloc struct pointer using sizeof?](http://stackoverflow.com/questions/29487252/whats-the-correct-way-to-malloc-struct-pointer-using-sizeof) – npostavs Apr 10 '15 at 21:08

0 Answers0