简体   繁体   中英

Why is “T *&root” being passed for insert operation in a binary tree?

I was creating a custom binary tree and has stumbled in the following code for correct insertion in the tree from this site .

void treeInsert(TreeNode *&root, string newItem) {
    if ( root == NULL ) {
        root = new TreeNode( newItem );
        return;
    }
    else if ( newItem < root->item ) {
        treeInsert( root->left, newItem );
    }
    else {
        treeInsert( root->right, newItem );
    }
}

Why do you need to passed TreeNode *&root instead of TreeNode *root ?

If you pass a pointer, rather than a reference to a pointer, modifications that you do to that pointer itself would be local to your treeInsert function. This prevents you from inserting the root - the only case when you must modify the pointer itself (the third line in your source code).

For example, if you do this

TreeNode *root = NULL;
treeInsert(root, "hello");

and treeInsert takes TreeNode* , the value of root after the call of treeInsert will remain NULL , because the third line of your source code would modify a local copy of the root pointer.

Consider the case when your newItem is the root item. Then this will change your root element. This means that at the end of the operation, your note 'root' has to point to the newly inserted TreeNode.

Now if you only pass TreeNode *root , you can only change the value, but at the end, your root pointer cannot be changed. So, you have to pass your pointer by reference, so that you can change it within your function.

The pointer TreeNode* is passed by reference, so that the original pointer in the calling function can be changed, in case the tree is empty.

Otherwise, if you just pass a copy of the pointer, the modifications will be local to the function being called.

A comment is present in the code itself: Note that root is passed by reference since its value can change in the case where the tree is empty.

If you don't do this, you have a NULL pointer in the calling function representing the root of the tree, which is clearly wrong since you just inserted an element.

Some other ways of handling the situation are:

  1. Returning the local root pointer

    root = treeInsert(root, str);

  2. Passing pointer to root pointer, so it can be changed

    treeInsert(&root, str);

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