我正在尝试在 C++ 中创建我的二叉树数据结构的深层副本。问题是我使用的代码似乎只给了我一个浅拷贝(这似乎导致我的解构器出现问题)。
下面的代码是我的二叉树复制构造函数:
BinaryTreeStorage::BinaryTreeStorage(const BinaryTreeStorage ©tree):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;
}
任何帮助,将不胜感激。谢谢
这是引发内存异常的解构函数(我相信这是因为我在上面做的浅拷贝)
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;
}
}