二叉搜索树析构函数问题

Binary Search Tree Destructor issue

本文关键字:问题 析构函数 搜索树      更新时间:2023-10-16

我目前正在将代码作为二叉搜索树的类代码,但是我的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;
        }
    }

问题是在我在 main 函数中使用赋值之后,例如:

BST bin_tree2=bin_tree1;

析构函数被调用,但在它删除bin_tree1中的数据后,放置在bin_tree2中的所有值都包含一些垃圾值,我收到该部分的错误。任何帮助将不胜感激。谢谢

看起来像您正在复制指针并在解除分配内存后访问它们。

问题似乎不在于我之前所说的键,而在于 BST::assgRec 函数中似乎构造不正确的节点。