删除节点调用时出现访问冲突错误

Access violation error on delete node call

本文关键字:访问冲突 错误 节点 调用 删除      更新时间:2023-10-16
// Delete a node
// (1) If leaf just delete
// (2) If only one child delete this node and replace
// with the child
// (3) If 2 children. Find the predecessor (or successor).
// Delete the predecessor (or successor). Replace the
// node to be deleted with the predecessor (or successor).
void Tree::deleteNode(int key)
{
    // Find the node.
    Node* thisKey = findNode(key, root);
    // (1)
    if ( thisKey->Left() == NULL && thisKey->Right() == NULL )
    {
        if ( thisKey->Key() > thisKey->Parent()->Key() )
            thisKey->Parent()->setRight(NULL);
        else
            thisKey->Parent()->setLeft(NULL);
        delete thisKey;
    }
    // (2)
    if ( thisKey->Left() == NULL && thisKey->Right() != NULL )
    {
        if ( thisKey->Key() > thisKey->Parent()->Key() )
            thisKey->Parent()->setRight(thisKey->Right());
        else
            thisKey->Parent()->setLeft(thisKey->Right());
        delete thisKey;
    }
    if ( thisKey->Left() != NULL && thisKey->Right() == NULL )
    {
        if ( thisKey->Key() > thisKey->Parent()->Key() )
            thisKey->Parent()->setRight(thisKey->Left());
        else
            thisKey->Parent()->setLeft(thisKey->Left());
        delete thisKey;
    }
    // (3)
    if ( thisKey->Left() != NULL && thisKey->Right() != NULL )
    {
        Node* sub = predecessor(thisKey->Key(), thisKey);
        if ( sub == NULL )
            sub = successor(thisKey->Key(), thisKey);        
        if ( sub->Parent()->Key() <= sub->Key() )
            sub->Parent()->setRight(sub->Right());
        else
            sub->Parent()->setLeft(sub->Left());
        thisKey->setKey(sub->Key());
        delete sub;
    }
}

我正在编写一个带有插入和删除功能的 BST。这是我的 deleteNode 函数的代码。当我尝试删除节点时,它会给我访问冲突错误并将程序发送到调试中。我不知道为什么。我在其他网站上读到你需要先清除节点,但我的教授告诉我,你可以搜索节点,找到它,然后删除它。

这是我创建树、打印树和删除两个节点的主要函数。

int main()
{
    //Create and insert nodes into tree.
    Tree* tree = new Tree();
    tree->addNode(5);
    tree->addNode(8);
    tree->addNode(3);
    tree->addNode(12);
    tree->addNode(9);
    cout<<" Inserting Nodes: 5, 8, 3, 12, and 9 sequentially. "<< endl;
    cout<<" -------------------"<< endl;
    cout<<" Here are the values in the tree (in-order traversal)" << endl;
    tree->print_inorder();
    cout << endl << endl;
    cout << "Deleting 8...." << endl;
    //tree->deleteNode(8); I get an access violation for the delete node functions.
    cout << "Deleting 12...." << endl;
    //tree->deleteNode(12);
    cout << "Now, here are the nodes (in-order traversal)" << endl;
    cout << "3 5 9" << endl;
    //tree->print_inorder();

提前感谢您提供的任何帮助!

当您在

某处损坏内存时,会发生访问冲突错误。由于您正在尝试删除节点,这意味着您要释放内存。最有可能的是,它应该是节点类的问题。

  • 您是否在节点类上提出了一个功能析构函数?

  • 检查您的代码是否尊重无效指针。

  • 您是否使用正确的 malloc(( 初始化了对象?

希望对您有所帮助。