简体   繁体   中英

Is it possible to copy a binary search tree by only passing a pointer as a parameter?

For an assignment, I am writing a copy constructor with a helper function.

binarytree::binarytree(binarytree& right) {
    copy(root, right.root);
}

And my copy function:

void binarytree::copy(treenode*& copyRoot, const treenode* root) {  

    if (root != nullptr) {
        //copy data

        //copy left
        copy(copyRoot->left, root->left);

        //copy right
        copy(copyRoot->right, root->right);
}

So far, works as intended to make a copy of the BST. However, my assignment specifies that the function will be static, void, and have two treenode* parameters. Is it possible to rewrite this function using treenode* copyRoot as a parameter instead of treenode*& copyRoot ?

If I change the function parameter just as is, the copy of the function is not being saved and is printing out an empty BST when I test.

Is it possible to rewrite this function using treenode* copyRoot as a parameter instead of treenode*& copyRoot?

I am making assumption that goal of binarytree::copy() is to create new copy of treenode (line copyRoot = new treenode(); suggest it), so for this case...

No, You can't do that.

By treenode*& copyRoot argument statement You are "returning" pointer, while treenode* copyRoot means that You are passing pointer to copy() method and in result inside copy() method in fact You have another copy of this pointer.

The best illustration for this case would be void cpy(int& i) and void cpy(int i) methods. The latter case doesn't change int passed to method. Now replace int by int* and this should be pretty straight forward explanation for Your question.

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