【发布时间】:2017-03-26 16:56:49
【问题描述】:
我目前正在将代码作为二叉搜索树的类代码,但在我的 BST 类的析构函数中出现错误。这是我的相关代码部分:
节点结构:
struct Node{
int key;
struct Node* left;
struct Node* right;
};
创建新节点的功能:
Node* BST::CreateNode(int key){
Node* temp_node = new Node();
temp_node->key = key;
temp_node->left = nullptr;
temp_node->right = nullptr;
return temp_node;
}
赋值运算符:
BST& BST::operator=(const BST& cpy_bst){
if (this != &cpy_bst){
Node* cpy_root = cpy_bst.root;
this->root=assgRec(cpy_root, this->root);
}
return *this;
}
Node* BST::assgRec(Node* src_root, Node* dest_root){
if (src_root != nullptr){
dest_root = CreateNode(src_root->key);
dest_root->left=assgRec(src_root->left, dest_root->left);
dest_root->right=assgRec(src_root->right, dest_root->right);
}
return src_root;
}
析构函数:
BST::~BST(){
DestroyNode(root);
}
void BST::DestroyNode(Node* r){
if (r != nullptr){
DestroyNode(r->left);
DestroyNode(r->right);
delete r;
}
}
问题是我在主函数中使用了赋值后,比如:
BST bin_tree2=bin_tree1;
调用了析构函数,但在它删除 bin_tree1 中的数据后,放置在 bin_tree2 中的所有值都包含一些垃圾值,我在该部分出现错误。任何帮助将不胜感激。谢谢
【问题讨论】:
-
错误是什么?
-
您好!这:DSAssg5.exe 中 0x00FA49DC 处未处理的异常:0xC0000005:访问冲突读取位置 0xDDDDDDE1。
-
请提供您的 Node 类的代码。
-
r = nullptr你想做什么?
标签: c++ binary-search-tree destructor