我目前正在为二叉搜索树做一个类代码,但是我的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。 – Hamza750
请提供您的Node类的代码。 – Lunar