简体   繁体   中英

Binary Search Tree Destructor issue

I am currently making a code a class code for binary search tree but I am getting an error in the destructor for my BST class. This is my relevant part of code:

Node Struct:

struct Node{
    int key;
    struct Node* left;
    struct Node* right;
};

Function to Create new node:

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;
}

Assignment Operator:

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;
}

Destructor:

BST::~BST(){

    DestroyNode(root);
}

 void BST::DestroyNode(Node* r){
        if (r != nullptr){
            DestroyNode(r->left);
            DestroyNode(r->right);
            delete r;
        }
    }

The problem is that after I have used the assignment in main function, like:

BST bin_tree2=bin_tree1;

The destructor is called but after it deletes the data in bin_tree1, all values that were placed in bin_tree2 have some junk values in them and I get an error on that part. Any help would be greatly appreciated. Thanks

This looks like you are copying pointers and accessing them after memory has been deallocated.

The problem seems not to be with the keys as I said earlier but with the nodes that seem to be improperly constructed in the BST::assgRec function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM