elminaa
elminaa

Reputation: 9

My insert code doesn't work correctly in c

I insert nodes a Binary Search Tree. But it doesn't work correctly. This is my code :

int adding(node * tree,double x,int y)
{   
    node *newN;

    if(!tree)
    {
        newN=(node*)malloc(sizeof(node));
        newN->data=x;
        newN->totalval=y;
        newN->right=NULL;
        newN->left=NULL;    
        tree=newN;
        return 1;   
    }               

    if(x < tree->data)
    {
        adding(tree->left,x,y);         
    }

    if(x==tree->data)
    {
        printf("This data is already existed. Please try again");
        return 0;
    }

    if(x> tree->data)
    {
        adding(tree->right,x,y);            
    }   
}

P.S : struct node has data , left, right . And in this insert data and x don't be the same. x is get from user and data is get from a folder and insert in different function.

Upvotes: 0

Views: 88

Answers (1)

David Haim
David Haim

Reputation: 26496

let's say tree is NULL. we sometime forget that a pointer is a number. the only extra is that this number is the offset of some byte in the memory, that's all.

so taking into account that null (in C) is (void*)0, this code:

if(!tree)
{
    newN=(node*)malloc(sizeof(node));
    newN->data=x;
    newN->totalval=y;
    newN->right=NULL;
    newN->left=NULL;    
    tree=newN;
    return 1;   
}

can be written like this:

 if(!tree)
    {
        //...
        (void*)0 = newN;
        return 1;   
    }

do you realize you try to assign a value to 0? what do we need to do in order to assign a value to a pointer, but not to the variable it points at? in other words, how should a function pass a pointer in order to change it ? (hint: as pointer to pointer)

Upvotes: 1

Related Questions