紅黑樹的刪除與維護
阿新 • • 發佈:2019-02-17
刪除後維護:void RBTreeDelete(RBTree z) { RBTree x,y; if(z->left == nil || z->right == nil) y = z; else y=TreeSuccessor(z); //y為z的中序後繼 if(y->left != nil) x = y->left; else x = y->right; x->parent = y->parent; if(y->parent == nil) root = x; else { if(y == y->parent->left) y->parent->left = x; else y->parent->right = x; } if(y != z) z->key = y->key; if(y->color == BLACK) RBTreeDeleteFixup(x); free(y); //VC6.0下這句好像有問題,可註釋掉。 }
查詢z的中序後繼:void RBTreeDeleteFixup(RBTree x) { RBTree w; while(x != root && x->color == BLACK){ if(x == x->parent->left){ w = x->parent->right; if(w->color == RED){ //case 1 w->color = BLACK; x->parent->color = RED; LeftRotate(x->parent); w = x->parent->right; } if(w->left->color == BLACK && w->right->color == BLACK){ //case 2 w->color = RED; x = x->parent; } else{ if(w->right->color == BLACK){ //case 3 w->left->color = BLACK; w->color = RED; RightRotate(w); w = x->parent->right; } w->color = x->parent->color; //case 4 x->parent->color = BLACK; w->right->color = BLACK; LeftRotate(x->parent); x = root; } } else{ w = x->parent->left; if(w->color == RED){ w->color = BLACK; x->parent->color = RED; RightRotate(x->parent); w = x->parent->left; } 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; LeftRotate(w); w = x->parent->left; } w->color = x->parent->color; x->parent->color = BLACK; w->left->color = BLACK; RightRotate(x->parent); x = root; } } } //endwhile x->color = BLACK; }