首页 > 解决方案 > 删除 AVL 树中的指针

问题描述

我一直在尝试制作平衡的二叉搜索树,目前正在制作删除功能。我试图删除元素的方式在旋转功能中起作用。

这是旋转功能:

void rightRotation(Object** currentNode)
    {
        auto child = (*currentNode)->leftChild;
        auto c_bf = child->getBalanceFactor();

        if (c_bf > 0) // RR rotation
        {
            auto originalNode = *currentNode;
            originalNode->leftChild = child->rightChild;
            child->rightChild = originalNode;
            *currentNode = child;
        }
        else // RL rotation
        {
            // -L part of the rotation
            auto originalChild = child;
            child = child->rightChild;
            (*currentNode)->leftChild = child;
            originalChild->rightChild = child->leftChild;
            child->leftChild = originalChild;
            // R- part of the rotation
            auto originalNode = *currentNode;
            originalNode->leftChild = child->rightChild;
            child->rightChild = originalNode;
            *currentNode = child;
        }
    }

因此,该函数获取节点地址的地址,并将该节点的地址替换为新节点(子节点)的地址。

我试图围绕相同的逻辑构建一个删除功能,但它不起作用,我不明白为什么。

这是删除功能:

void del(Object** node)
    {
        if ((*node)->leftChild == NULL and (*node)->rightChild == NULL) // current node is a leaf
        {
            delete (*node);
            (*node) = NULL;

            //return;
        }
        else if ((*node)->rightChild == NULL)
        {
            auto newNode = (*node)->leftChild;
            delete (*node);
            (*node) = newNode;

            //return;
        }
        else if((*node)->leftChild == NULL)
        {
            auto newNode = (*node)->rightChild;
            delete (*node);
            (*node) = newNode;

            //return;
        }
        else // we have both childs 
        {
            // find the smallest element bigger than the current node
            // it will be the leftest element of the right child

            auto replacementNode = (*node)->rightChild;
            while (replacementNode->leftChild != NULL)
                replacementNode = replacementNode->leftChild;

            auto copy = new Object(*replacementNode);
            copy->leftChild = (*node)->leftChild;
            copy->rightChild = (*node)->rightChild;
            delete (*node);
            (*node) = copy;
            del(&replacementNode);
        }

        balance();
    }

我尝试调试,进入删除功能的地址与我从 &this->root->leftChild 获得的地址不同(我试图删除这个节点)

整个代码

标签: c++pointers

解决方案


推荐阅读