Bst- 为什么我的 Best 在将 node* 更改为 node*& 后工作?

Bst- Why did my Bst worked after chaning node* to node*&?

我实现了 BST,我的实现看起来像这样

 void insert(node*&r,int key){      // 1 ) node* r 2) node*&r
    if(r==NULL){
        r=new node(key);
        return;
    }
    c++;
    if(r->key > key){
        insert(r->right,key);
    }
    else if(r->key <key){
        insert(r->left,key);
    }
  }

int main()
{
    int n;
    cin>>n;
    node *root=NULL;
    for(int i=0;i<n;i++){
        int x;
        cin>>x;
        insert(root,x);
    }
    return 0;
}

我之前很清楚为什么node*&不是node*。但是我有心理障碍today.I很困惑如果我们使用 node*& 那么我们将永久编辑作为 BST 身份的根因此我们将松开 BST.On 另一方面我很困惑为什么它不起作用关于使用 node*。谁能在 detail.Which 中解释一下,为什么?

它现在可以工作了,因为您通过引用传递了指针,因此传递它的函数可以修改它。否则,您按值传递指针,并且在函数退出时,作为参数传递的指针不会被修改。

看看这里发生了什么:

node *root=NULL; // so initially root is nullptr

然后,在 for 循环中,您有

insert(root,x); // better take it by reference, otherwise root is not modified

在插入退出时,root 被修改 只有当 通过引用传递时,否则,如果通过值传递,它保持 NULL。请记住,指针的行为与任何其他变量一样,在 C++ 中,它默认按值传递。