C++: Pointer vs Pointer of Pointer to insert a node in a Binary Tree

对着背影说爱祢 提交于 2019-12-01 18:19:19

The first code should not compile. In fact it doesn't compile under MSVC 2013.

Why ?

Your node structure should be something like this:

struct Nodo {
    int value; 
    Nodo*left, *right;  // pointer to the children nodes
};

This means that (root)->left is of type Nodo*. Hence &(root)->left is of type Nodo** which is incompatible with a Nodo* argument.

Anyway, in your insert function, you certainly want to change the tree. But if you'd for example do: root = n; you would just update the root argument (pointer). This update is lost as soon as you leave the function. Here, you certainly want to change either the content of the root node or more probably the pointer to a root node.

In the second version, you pass as argument the address of a pointer to a node, and then update this pointer when necessary (expected behaviour).

Remark

The first version could be "saved", if you would go for a pass by reference:

void Insert(Nodo * &root, int x){  // root then refers to the original pointer 
   if(root == NULL){   // if the original poitner is null... 
      Nodo *n = new Nodo();
      n->value = x
      root = n;        // the orginal pointer would be changed via the reference    
      return;
   }
   else{
      if(root->value > x)
         Insert(root->left, x);   // argument is the pointer that could be updated
      else
         Insert(root->right, x);
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!