*&在这里做什么?如何更改它以获取代码作为 void binaryTree::insert(binaryNode *root,string value)?可能吗?

What is *& doing here? How do I change it to get a code as just void binaryTree::insert(binaryNode *root,string value)? Is it possible?

本文关键字:binaryNode root insert string value binaryTree 什么 在这里 何更改 取代码 获取      更新时间:2023-10-16
void binaryTree::insert(binaryNode *&root,string value)
{
    if(root==NULL)
        root = CreateNode(value);
    else if( value > root->data )
        insert (root->right,value);
    else if( value < root->data )
        insert (root->left,value);
}

binaryNode *&表示对指向类型 binaryNode 的指针的引用。因为它是一个引用,所以此语句root = CreateNode(value);修改root引用的内容,而不是更改root本身。

因此,如果您将其替换为 binaryNode * ,该语句将不起作用,因为您刚刚修改了此堆栈帧上的root,并且当函数返回时,此变量将被销毁。

您需要将指针传递给指针:

void binaryTree::insert(binaryNode **root,string value)
{
    if(*root==nullptr)
        *root = CreateNode(value);
    else if( value > *root->data )
        *root = insert (*root->right,value);
    else if( value < *root->data )
        *root = insert (*root->left,value);
    return root;
}

或者让函数将指针返回到调用方:

binaryNode *binaryTree::insert(binaryNode *root,string value)
{
    if(root==nullptr)
        root = CreateNode(value);
    else if( value > root->data )
        root = insert (root->right,value);
    else if( value < root->data )
        root = insert (root->left,value);
    return root;
}

显然,在后者中,调用 insert() 会略有不同,因为您需要将结果分配给第一个参数:

someTree = binaryTree::insert(someTree, someString);