简体   繁体   中英

c++ reference type as recursive function parameter

Node * BST::insert_real(int key, Node *& node)
{
    if (node == nullptr)
        return node = new Node(key);

    if (key < node->key)
        return insert_real(key, node->left);
    else if (key > node->key)
        return insert_real(key, node->right);
    else
        return nullptr;
}

Node * BST::insert(int key)
{
    return insert_real(key, header->left);
}

BinarySearchTree, the insert function.

If the key always goes left , when the function insert_all() runs to the position node = new Node(key) , whether the node is equivalent to header->left->left->left->left->left->......->left->left ?

if my guess above is right, the code header->left->left->left->left->left->......->left->left will bring some burden.(if so, i will replace Node*& with Node** )


The words I say above is right?

If the key always goes left, when the function insert_all() runs to the position node = new Node(key) , whether the node is equivalent to header->left->left->left->left->left->......->left->left

No, in the below call you are not changing node parameter which you received.You are just calling insert_real() with some other parameter.

return insert_real(key, node->left);

The only time you change node is below

if (node == nullptr)
    return node = new Node(key);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM