简体   繁体   中英

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!

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).

First of all, thank you for asking this question. As I was also doing the implementation of BT(BINARY TREE ).The answer of your question lies in the full part of the program.

If you declare the root / head pointer externally then you don't need to use double pointer. But iIf you declare the root pointer inside the main function. Then we come up with 2 possibilities:

As you know we declare root as NULL in the starting point inside the main

  1. When you call the insert method and you put the parameters as root and data then you will collect in the insert function as local root pointer variable. Even if you change the links of root local that doesn't create any effect on the (main) root, so that's why you have to declare double pointer in the insert function. Then if you do some compute with root then it will go for (real)main, and if you are using double pointer then by recursion you'll send an address to double pointer so you have to send the address of a pointer though it will effect the actual pointer that you called
  2. Next approach is either you can return the address of root at every calling of the insert method and collect it inside the root and compute everything normal like as in recursive doubly linked list inside insert method

EG:. root=insert(root,data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM