红黑树固定插入

时间:2013-04-13 11:48:15

标签: c++ algorithm insertion red-black-tree

我正在使用RB树创建自己的Map结构(类需要)。根据我对插入的了解,我们有3个案例需要处理。我正在关注this实施。在修复RB树结构时插入第3个值(以及任何其他值)后,我仍然遇到内存违规。我该如何处理这个案子?

插入儿童:

Image

所以这是我的实施:

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。如何更改功能?

2 个答案:

答案 0 :(得分:2)

您正在使用依赖于标记节点作为叶节点的实现,因此您总是有一个黑色节点,您可以在这种情况下解除引用。要更改它,您必须更改

等行
if(uncle->color == 1)   

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

然后它将采用'else'子句,就像在哨兵版本中一样,在非哨兵版本中你有一个空指针的情况下,颜色总是黑色。

答案 1 :(得分:0)

RotateLeft(child->Parent);

RotateRight(child->Parent);

您的代码中的上述内容不应该

分别为

RotateLeft(child)RotateRight(child)