-2
BST::BST()

{
    
root = nullptr;

}

BST::BST(const BST& rhs)

{

    root = rhs.root;
    root->left = rhs.root->left;
    root->left = rhs.root->left;


    TreeNode* DeepCopy = new TreeNode;
    if (root != nullptr)
    {
        DeepCopy->info = rhs.root->info;
        DeepCopy->left = rhs.root->left;
        DeepCopy->right = rhs.root->right;
    }

// Will this make a deep copy of the entire tree?

}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Raiin
  • 35
  • 1
  • 6
  • _`// Will this make a deep copy of the entire tree?`_ Doesn't look so. – πάντα ῥεῖ Nov 19 '20 at 18:55
  • Do you really need a copy constructor? Also, decide on whether you will copy the nodes or make more links to the existing nodes? Smart Pointers? – Thomas Matthews Nov 19 '20 at 18:59
  • `DeepCopy` is a local variable. All you do to it will have no effect on anything else. The object will not be deleted at the end of the function but you also have no reference to it and you cannot get any. Its a costly way to create a leak – 463035818_is_not_an_ai Nov 19 '20 at 19:00

1 Answers1

1

No. Golden rule, copying a pointer copies the pointer, not what the pointer is pointing at. Beginners often are confused about this.

One way write a deep copying copy constructor is to write a normal recursive routine that copies the tree structure and call that routine from your copy constructor. Something like this

BST::BST(const BST& rhs) : root(deep_copy(rhs.root))
{
}

// recursive routine to copy the tree structure
friend TreeNode* deep_copy(TreeNode* rhs)
{
    if (rhs)
    {
        TreeNode* lhs = new TreeNode();
        lhs->info = rhs->info;
        lhs->left = deep_copy(rhs->left);
        lhs->right = deep_copy(rhs->right);
        return lhs;
    }
    else
    {
        return nullptr;
    }
}
john
  • 85,011
  • 4
  • 57
  • 81