简体   繁体   English

具有参数引用的二进制搜索树插入

[英]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. 它有效,但是我不明白为什么要传递对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 . 您希望函数能够更改存储在要插入的节点的父节点中的指针,使其指向新节点而不是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. 该函数将使用right指针作为参数来调用。 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. 如果不传递引用,则该函数将无法更改节点的right指针,因为它仅获得了一个副本。 Using the reference allows the function to actually modify the pointer stored in the node that was used as the argument. 使用引用允许函数实际修改存储在用作参数的节点中的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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