1

RB ツリーを使用して、独自の Map 構造 (クラスに必要) を作成しています。挿入について学んだことから、処理するケースが 3 つあります。私はこの実装に従っています。それでも、RB ツリー構造を修正している間に 3 番目の値 (およびそれ以上) を挿入した後、メモリ違反が発生します。このケースをどのように処理しますか?

子が挿入されます:

画像

だからここに私の実装があります:

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。機能を変更するにはどうすればよいですか?

4

2 に答える 2

0
RotateLeft(child->Parent);

RotateRight(child->Parent);

あなたのコードの上記はすべきではありません

RotateLeft(child)そしてRotateRight(child)それぞれ。

于 2016-10-21T23:47:25.523 に答える