简体   繁体   中英

binary search tree insertion with argument reference

I wrote the following function to practice binary search tree insertion:

void RecursiveInsert(struct Node* &root, int key) {

    if (root == nullptr) {
        root = new Node(key);
        return;
    } else if (root->key > key) {
        RecursiveInsert(root->left, key);
    } else {
        RecursiveInsert(root->right, key);
    }
}

It works, but I don't understand why should I pass in a reference to root. Does anybody know why?

You want the function to be able to change the pointer stored in the parent node of the node that you're going to insert so that it points to the new node instead of nullptr . If you don't use pass-by-reference, all the function can do is modify a local copy of the pointer, and the pointer in the actual tree won't get changed.

For example, let's say you're looking at a node, and you want to insert the new node as this node's right child.

someNode[key: 123, left: nullptr, right: nullptr]

The function is going to be called with the right pointer as an argument. You want the function to be able to change the node so it looks like this:

someNode[key: 123, left: nullptr, right: newNode]

If you don't pass-by-reference, the function can't change the right pointer of the node, since it has only been given a copy. Using the reference allows the function to actually modify the pointer stored in the node that was used as the argument.

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