【问题标题】:Binary Search Tree Destructor issue二叉搜索树析构函数问题
【发布时间】: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 中的所有值都包含一些垃圾值,我在该部分出现错误。任何帮助将不胜感激。谢谢

【问题讨论】:

标签: c++ binary-search-tree destructor


【解决方案1】:

这看起来像是在复制指针并在内存被释放后访问它们。

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

【讨论】:

  • 正是这个问题,但我到底是怎么得到它的?据我所知,我只是将 src_root 的 key 的值复制到 dest_root 的 key 中。
猜你喜欢
  • 2011-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
相关资源
最近更新 更多