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

前端 未结 1 617
刺人心
刺人心 2021-01-19 01:57

I was creating a function to insert a element in a binary tree and, first, i did the following on Visual Studio 2012:

void Insert(Nodo *root, int x){
   if(r         


        
相关标签:
1条回答
  • 2021-01-19 02:28

    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);
       }
    }
    
    0 讨论(0)
提交回复
热议问题