Search code examples
c++binary-treecopy-constructordeep-copyshallow-copy

Deep Copy Constructor for binary tree


I am trying to create a deep copy of my binary tree data structure in C++. The problem is the code I am using only seems to be giving me a shallow copy (which seems to cause problems with my deconstructor).

the code below is my binary tree copy constructor:

BinaryTreeStorage::BinaryTreeStorage(const BinaryTreeStorage &copytree):root(NULL)
{
    root = copytree.root;
    copyTree(root);
}

BinaryTreeStorage::node* BinaryTreeStorage::copyTree(node* other)
{
    //if node is empty (at bottom of binary tree)
    /*
        This creates a shallow copy which in turn causes a problem 
        with the deconstructor, could not work out how to create a 
        deep copy.
    */
    if (other == NULL)
    {
        return NULL;
    }

    node* newNode = new node;

    if (other ->nodeValue == "")
    {
        newNode ->nodeValue = "";
    }

    newNode->left = copyTree(other->left);
    newNode->right = copyTree(other->right); 

    return newNode;
}

Any help would be appreciated. Thanks

Here is the deconstructor that throws a memory exception (which i believe is because of the shallow copy i do above)

BinaryTreeStorage::~BinaryTreeStorage(void)
{
    try
    {
        destroy_tree();//Call the destroy tree method
        delete root;//delete final node
    }
    catch(int &error)
    {
        cout << "Error Message : " << error << endl;
    }
}
void BinaryTreeStorage::destroy_tree()
{
    destroy_tree(root);
}
void BinaryTreeStorage::destroy_tree(node *leaf)
{
  if(leaf!=NULL)
  {
    //Recursively work way to bottom node 
    destroy_tree(leaf->left);
    destroy_tree(leaf->right);
    //delete node
    delete leaf;
 }
}

Solution

  • You're not performing a deep copy of your root node, only its children.

    Shouldn't it be:

    root = copyTree(copytree.root);
    

    ?

    EDIT: In addition, you destroy the root twice:

    destroy_tree();//Call the destroy tree method
    
    //once here
    //remove this line
    delete root;//delete final node
    

    and

    if(leaf!=NULL)
    {
       //Recursively work way to bottom node 
       destroy_tree(leaf->left);
       destroy_tree(leaf->right);
    
       //one more time here
       delete leaf;
    }
    

    If you only do one of these fixes, the problem won't be solved.