Search code examples
cpointersbinary-treedouble-pointer

Confused with the usage of double pointers insertion of nodes in a Binary Tree


So here is the function that works fine:

void Insert(node ** root, int inpdata){//tree's root should be passed here
   if(*root == NULL){
        *root = createNode(inpdata);
    }
   else if(inpdata < (*root)->data){
        Insert(&(*root)->left,inpdata);
    }
   else{
        Insert(&(*root)->right,inpdata);
    }
}

But I could not figure out why we have to use a double pointer. Why wouldn't the following code work for instance:

void Insert(node * root, int inpdata){//tree's root should be passed here
    if(root == NULL){
        root = createNode(inpdata);
    }
    else if(inpdata < root->data){
        Insert(root->left,inpdata);
    }
    else{
        Insert(root->right,inpdata);
    }
}

Also, in the first function, I could not comprehend the usage of &(*root).Wouldn't that make no sense because *root itself is a pointer. So, the "address of a pointer" is redundant since pointer already stores an adress value. I might be a bit confused so a little help would be much appreciated.
Thanks!


Solution

  • C passes argument by value, if you use then second approach:

    void Insert(node * root, int inpdata);
    

    After calling this function, the root in the caller side won't be affected.

    I could not comprehend the usage of &(*root)

    You are confused by precedence and wrongly parse the expression. &(*root)->left is

    &((*root)->left).