我正在使用RB树创建自己的Map结构(该类需要)。从我对插入的了解中,我们可以处理3种情况。我正在关注this实现。在修复RB树结构的同时插入第三个值(以及其他值)后,仍然遇到内存冲突问题。我该如何处理?

child 被插入:

所以这是我的实现:

struct Node
{
    pair<int,int> key;
    int Value;
    Node *LeftNode;
    Node *RightNode;
    Node *Parent;
    bool color;                 // 0 - black 1 - red
};

class Map
{
    int size;

public:
    Map();
    void insert(pair<int,int>, int);

private:
    void RotateLeft(Node*);
    void RotateRight(Node*);
    void InsertNode(Node*, pair <int,int>, int);
    void RestoreColor(Node*);

    Node* root;
};

void Map::RestoreColor(Node* child)
{
    while( child->Parent!=root && child->Parent->color==1 )
    {
        if(child->Parent == child->Parent->Parent->LeftNode)
        {
            Node* uncle = child->Parent->Parent->RightNode;

            if(uncle->color == 1)
            {
                child->Parent->color = 0;
                uncle->color = 0;
                child->Parent->Parent->color = 1;
                child = child->Parent->Parent;
            }else
            {
                if(child = child->Parent->RightNode)
                {
                    child = child->Parent;
                    RotateLeft(child->Parent);
                }
                child->Parent->color = 0;
                child->Parent->Parent->color= 1;
                RotateRight(child->Parent->Parent);
            }
        }else
        {
            if(child->Parent == child->Parent->Parent->RightNode)
            {
                Node* uncle = child->Parent->Parent->LeftNode;

                if(uncle->color == 1)                                                           {
                    child->Parent->color = 0;
                    uncle->color = 0;
                    child->Parent->Parent->color = 1;
                    child = child->Parent->Parent;
                }else
                {
                    if(child = child->Parent->LeftNode)
                    {
                        child = child->Parent;
                        RotateRight(child->Parent);
                    }
                    child->Parent->color = 0;
                    child->Parent->Parent->color= 1;
                    RotateLeft(child->Parent->Parent);
                }
            }
        }
        root->color=0;
    }
};

违反行为发生在uncle访问中,在此示例中uncle等于null。如何更改功能?

最佳答案

您使用的是一个依赖于哨兵节点作为叶节点的实现,因此,在这种情况下,您总会有一个黑色节点可以取消引用。要更改它,您必须更改以下行

if(uncle->color == 1)


if((uncle != NULL) && (uncle->color == 1))

然后,它将像在前哨版本中一样采用'else'子句,如果在非前哨版本中使用空指针,则颜色将始终为黑色。

10-08 04:08