二叉树的深度复制构造函数

bri*_*342 5 c++ binary-tree deep-copy copy-constructor shallow-copy

我正在尝试用 C++ 创建二叉树数据结构的深层副本。问题是我使用的代码似乎只给了我一个浅拷贝(这似乎导致我的解构函数出现问题)。

下面的代码是我的二叉树复制构造函数:

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;
}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激。谢谢

这是抛出内存异常的解构函数(我相信这是因为我上面所做的浅复制)

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;
 }
}
Run Code Online (Sandbox Code Playgroud)

Luc*_*ore 5

您没有执行根节点的深层复制,而只是执行其子节点的深层复制。

不应该是:

root = copyTree(copytree.root);
Run Code Online (Sandbox Code Playgroud)

编辑:此外,您还销毁了root两次:

destroy_tree();//Call the destroy tree method

//once here
//remove this line
delete root;//delete final node
Run Code Online (Sandbox Code Playgroud)

if(leaf!=NULL)
{
   //Recursively work way to bottom node 
   destroy_tree(leaf->left);
   destroy_tree(leaf->right);

   //one more time here
   delete leaf;
}
Run Code Online (Sandbox Code Playgroud)

如果您只执行其中一项修复,问题将无法解决。