224{
226 while (p != root && p->color == 'b')
227 {
228 if (p->parent->left == p)
229 {
230 s = p->parent->right;
231 if (s->color == 'r')
232 {
233 s->color = 'b';
234 p->parent->color = 'r';
235 leftrotate(p->parent);
236 s = p->parent->right;
237 }
238 if (s->right->color == 'b'&&s->left->color == 'b')
239 {
240 s->color = 'r';
241 p = p->parent;
242 }
243 else
244 {
245 if (s->right->color == 'b')
246 {
247 s->left->color = 'b';
248 s->color = 'r';
249 rightrotate(s);
250 s = p->parent->right;
251 }
252 s->color = p->parent->color;
253 p->parent->color = 'b';
254 s->right->color = 'b';
255 leftrotate(p->parent);
256 p = root;
257 }
258 }
259 else
260 {
261 s = p->parent->left;
262 if (s->color == 'r')
263 {
264 s->color = 'b';
265 p->parent->color = 'r';
266 rightrotate(p->parent);
267 s = p->parent->left;
268 }
269 if (s->left->color == 'b'&&s->right->color == 'b')
270 {
271 s->color = 'r';
272 p = p->parent;
273 }
274 else
275 {
276 if (s->left->color == 'b')
277 {
278 s->right->color = 'b';
279 s->color = 'r';
280 leftrotate(s);
281 s = p->parent->left;
282 }
283 s->color = p->parent->color;
284 p->parent->color = 'b';
285 s->left->color = 'b';
286 rightrotate(p->parent);
287 p = root;
288 }
289 }
290 p->color = 'b';
291 root->color = 'b';
292 }
293}