删除节点调用上的访问冲突错误

时间:2014-04-07 18:35:42

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

// 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();

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

1 个答案:

答案 0 :(得分:2)

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

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

  • 检查代码是否存在无效指针。

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

希望它有所帮助。