0 / 0 / 0
Регистрация: 15.12.2017
Сообщений: 18
1

Красно-черные деревья. Реализация

25.11.2020, 17:01. Показов 1835. Ответов 0

Author24 — интернет-сервис помощи студентам
Здравствуйте! Помогите, пожалуйста, исправить ошибку в коде
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
 
 
/* implementation dependend declarations */
typedef enum {
    STATUS_OK,
    STATUS_MEM_EXHAUSTED,
    STATUS_DUPLICATE_KEY,
    STATUS_KEY_NOT_FOUND
} statusEnum;
 
typedef int keyType;            /* type of key */
 
/* user data stored in tree */
typedef struct {
    int stuff;                  /* optional related data */
} recType;
 
#define compLT(a,b) (a < b)
#define compEQ(a,b) (a == b)
 
/* implementation independent declarations */
/* Red-Black tree description */
typedef enum { BLACK, RED } nodeColor;
 
typedef struct nodeTag {
    struct nodeTag *left;       /* left child */
    struct nodeTag *right;      /* right child */
    struct nodeTag *parent;     /* parent */
    nodeColor color;            /* node color (BLACK, RED) */
    keyType key;                /* key used for searching */
    recType rec;                /* user data */
} nodeType;
 
#define NIL &sentinel           /* all leafs are sentinels */
nodeType sentinel = { NIL, NIL, 0, BLACK, 0};
 
nodeType *root = NIL;               /* root of Red-Black tree */
 
void rotateLeft(nodeType *x) {
 
   /**************************
    *  rotate node x to left *
    **************************/
 
    nodeType *y = x->right;
 
    /* establish x->right link */
    x->right = y->left;
    if (y->left != NIL) y->left->parent = x;
 
    /* establish y->parent link */
    if (y != NIL) y->parent = x->parent;
    if (x->parent) {
        if (x == x->parent->left)
            x->parent->left = y;
        else
            x->parent->right = y;
    } else {
        root = y;
    }
 
    /* link x and y */
    y->left = x;
    if (x != NIL) x->parent = y;
}
 
void rotateRight(nodeType *x) {
 
   /****************************
    *  rotate node x to right  *
    ****************************/
 
    nodeType *y = x->left;
 
    /* establish x->left link */
    x->left = y->right;
    if (y->right != NIL) y->right->parent = x;
 
    /* establish y->parent link */
    if (y != NIL) y->parent = x->parent;
    if (x->parent) {
        if (x == x->parent->right)
            x->parent->right = y;
        else
            x->parent->left = y;
    } else {
        root = y;
    }
 
    /* link x and y */
    y->right = x;
    if (x != NIL) x->parent = y;
}
 
void insertFixup(nodeType *x) {
 
   /*************************************
    *  maintain Red-Black tree balance  *
    *  after inserting node x           *
    *************************************/
 
    /* check Red-Black properties */
    while (x != root && x->parent->color == RED) {
        /* we have a violation */
        if (x->parent == x->parent->parent->left) {
            nodeType *y = x->parent->parent->right;
            if (y->color == RED) {
 
                /* uncle is RED */
                x->parent->color = BLACK;
                y->color = BLACK;
                x->parent->parent->color = RED;
                x = x->parent->parent;
            } else {
 
                /* uncle is BLACK */
                if (x == x->parent->right) {
                    /* make x a left child */
                    x = x->parent;
                    rotateLeft(x);
                }
 
                /* recolor and rotate */
                x->parent->color = BLACK;
                x->parent->parent->color = RED;
                rotateRight(x->parent->parent);
            }
        } else {
 
            /* mirror image of above code */
            nodeType *y = x->parent->parent->left;
            if (y->color == RED) {
 
                /* uncle is RED */
                x->parent->color = BLACK;
                y->color = BLACK;
                x->parent->parent->color = RED;
                x = x->parent->parent;
            } else {
 
                /* uncle is BLACK */
                if (x == x->parent->left) {
                    x = x->parent;
                    rotateRight(x);
                }
                x->parent->color = BLACK;
                x->parent->parent->color = RED;
                rotateLeft(x->parent->parent);
            }
        }
    }
    root->color = BLACK;
}
 
statusEnum insert(keyType key, recType *rec) {
    nodeType *current, *parent, *x;
 
   /***********************************************
    *  allocate node for data and insert in tree  *
    ***********************************************/
 
    /* find future parent */
    current = root;
    parent = 0;
    while (current != NIL) {
        if (compEQ(key, current->key)) 
            return STATUS_DUPLICATE_KEY;
        parent = current;
        current = compLT(key, current->key) ?
            current->left : current->right;
    }
 
    /* setup new node */
    if ((x = malloc (sizeof(*x))) == 0)
        return STATUS_MEM_EXHAUSTED;
    x->parent = parent;
    x->left = NIL;
    x->right = NIL;
    x->color = RED;
    x->key = key;
    x->rec = *rec;
 
    /* insert node in tree */
    if(parent) {
        if(compLT(key, parent->key))
            parent->left = x;
        else
            parent->right = x;
    } else {
        root = x;
    }
 
    insertFixup(x);
 
    return STATUS_OK;
}
 
void deleteFixup(nodeType *x) {
 
   /*************************************
    *  maintain Red-Black tree balance  *
    *  after deleting node x            *
    *************************************/
 
    while (x != root && x->color == BLACK) {
        if (x == x->parent->left) {
            nodeType *w = x->parent->right;
            if (w->color == RED) {
                w->color = BLACK;
                x->parent->color = RED;
                rotateLeft (x->parent);
                w = x->parent->right;
            }
            if (w->left->color == BLACK && w->right->color == BLACK) {
                w->color = RED;
                x = x->parent;
            } else {
                if (w->right->color == BLACK) {
                    w->left->color = BLACK;
                    w->color = RED;
                    rotateRight (w);
                    w = x->parent->right;
                }
                w->color = x->parent->color;
                x->parent->color = BLACK;
                w->right->color = BLACK;
                rotateLeft (x->parent);
                x = root;
            }
        } else {
            nodeType *w = x->parent->left;
            if (w->color == RED) {
                w->color = BLACK;
                x->parent->color = RED;
                rotateRight (x->parent);
                w = x->parent->left;
            }
            if (w->right->color == BLACK && w->left->color == BLACK) {
                w->color = RED;
                x = x->parent;
            } else {
                if (w->left->color == BLACK) {
                    w->right->color = BLACK;
                    w->color = RED;
                    rotateLeft (w);
                    w = x->parent->left;
                }
                w->color = x->parent->color;
                x->parent->color = BLACK;
                w->left->color = BLACK;
                rotateRight (x->parent);
                x = root;
            }
        }
    }
    x->color = BLACK;
}
 
statusEnum delete(keyType key) {
    nodeType *x, *y, *z;
 
   /*****************************
    *  delete node z from tree  *
    *****************************/
 
    /* find node in tree */
    z = root;
    while(z != NIL) {
        if(compEQ(key, z->key)) 
            break;
        else
            z = compLT(key, z->key) ? z->left : z->right;
    }
    if (z == NIL) return STATUS_KEY_NOT_FOUND;
 
    if (z->left == NIL || z->right == NIL) {
        /* y has a NIL node as a child */
        y = z;
    } else {
        /* find tree successor with a NIL node as a child */
        y = z->right;
        while (y->left != NIL) y = y->left;
    }
 
    /* x is y's only child */
    if (y->left != NIL)
        x = y->left;
    else
        x = y->right;
 
    /* remove y from the parent chain */
    x->parent = y->parent;
    if (y->parent)
        if (y == y->parent->left)
            y->parent->left = x;
        else
            y->parent->right = x;
    else
        root = x;
 
    if (y != z) {
        z->key = y->key;
        z->rec = y->rec;
    }
 
 
    if (y->color == BLACK)
        deleteFixup (x);
 
    free (y);
    return STATUS_OK;
}
 
statusEnum find(keyType key, recType *rec) {
 
   /*******************************
    *  find node containing data  *
    *******************************/
 
    nodeType *current = root;
    while(current != NIL) {
        if(compEQ(key, current->key)) {
            *rec = current->rec;
            return STATUS_OK;
        } else {
            current = compLT (key, current->key) ?
                current->left : current->right;
        }
    }
    return STATUS_KEY_NOT_FOUND;
}
 
 
void main(int argc, char **argv) {
    int maxnum, ct;
    recType rec;
    keyType key;
    statusEnum status;
 
    /* command-line:
     *
     *   rbt maxnum
     *
     *   rbt 2000
     *       process 2000 records
     *
     */
 
    maxnum = atoi(argv[1]);
 
    printf("maxnum = %d\n", maxnum);
    for (ct = maxnum; ct; ct--) {
        key = rand() % 9 + 1;
        if ((status = find(key, &rec)) == STATUS_OK) {
            status = delete(key);
            if (status) printf("fail: status = %d\n", status);
        } else {
            status = insert(key, &rec);
            if (status) printf("fail: status = %d\n", status);
        }
    }
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
25.11.2020, 17:01
Ответы с готовыми решениями:

Красно-черные деревья
Здравствуйте. Подскажите пожалуйста как такую задачу переделать под КЧД. Задача: написать...

Красно-черные деревья
Здравствуйте. У меня проблема с реализацией КЧД. #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt;...

Красно-черные деревья: добавление, удаление, печать
В общем, проблема такая, что у меня Красно-черные деревья Нужно просто реализовать добавление,...

Класс "Красно черные деревья"
Народ,нужен доступно-понятный класс КЧД,желательно с определенными методами вращений,добавления...

0
25.11.2020, 17:01
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
25.11.2020, 17:01
Помогаю со студенческими работами здесь

Красные и черные деревья
Здравствуйте! Помогите пожалуста. Не компилируется программа, ошибка в 159 строке. вот код : ...

Реализация красно-черного дерева
Нужна помощь с красно-черным деревом;) Как свести эти части кода в одно целое, нужно чтобы после...

Максимально простая реализация красно-чёрного дерева
Здравствуйте, извините что тема не заставит напрячь Вас свои шестерёнки. Мне необходима МАКСИМАЛЬНО...

Красно-черное дерево (класс, шаблон и его реализация)
всем привет, у меня возникла проблема в создании шаблона, в обычном виде т.е. в не шаблонном, он...

"красно чорные" деревья
Здорова! Нужно вообщем построить дерево, токо не обычное дерево, а &quot;красно чорное&quot;. Я начитал...

Курсач по теме: Структуры данных. Двоичные деревья поиска. Красно-черные деревья
Здравствуйте, я первокурсник, преподавателя по информатике месяца 2 не было, потом появился, дал...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru