Bst-为什么我的Bst在将节点*追逐到节点*&后起作用?

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

本文关键字:节点 起作用 追逐 为什么 Bst Bst- 我的      更新时间:2023-10-16

我实现了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;
}

我之前很清楚为什么节点*&不是节点*。但我今天有心理障碍。我感到困惑的是,如果我们使用节点*&则我们将永久编辑作为BST标识的根,因此我们将释放BST。另一方面,我很困惑为什么它在使用节点*时不起作用。有人能详细解释一下吗。哪一个,为什么?

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

看看这里发生了什么:

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++中,默认情况下是按值传递的。