我差不多完成了一棵红黑树,但我的删除功能出现故障。它可能会删除它可能没有的节点。删除根目录并按下打印选项后,我的屏幕上发送了我已经在树中的节点。在2,1,7,5,8,11,14,15,4
的测试树中,如果我删除root=7
并按顺序打印,我会获得2,4,5,8,1,2,4,5,8,1,.....
,依此类推,直到程序崩溃。如果我删除2程序立即崩溃。节点11像1-4-15之类的所有叶子一样删除精细。我试图通过调试找到问题,但一切似乎都运行正常。该代码基于Cormen对算法的介绍。谢谢!
void RB_delete(struct node* z,struct node* y) //delete z y=z on call
{
struct node *x;
enum type originalcolor; //x moves into y's original position
originalcolor=y->color; // Keep track of original color
if (z->LC==nill) //case 1: (z has no LC)
{
x=z->RC;
RB_transplant(z,z->RC);
else if (z->RC==nill) //case 2: z has LC but no RC
{
x=z->LC;
RB_transplant(z,z->LC);
}
else // two cases: z has both Children
{
y=tree_minimum(z->RC); //find successor
originalcolor=y->color; //save color of successor
x=y->RC;
if (y->P==z) //successor has no LC cause its nill
x->P=y;
else
{
RB_transplant(y,y->RC);
y->RC=z->RC;
y->RC->P=y;
}
RB_transplant(z,y);
y->LC=z->LC;
y->LC->P=y;
y->color=z->color;
}
if (originalcolor == black)
RB_delete_fix(x);
free(z);
}
void io_print(struct node *aux,struct node *auxnill)
{
HANDLE hConsole;
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
if(aux != auxnill)
{
io_print(aux->LC,auxnill);
if (aux->color==red)
{
SetConsoleTextAttribute(hConsole, 12);
printf("%d,\n",aux->key);fflush(stdout);
SetConsoleTextAttribute(hConsole, 15);
}
if (aux->color==black)
{
SetConsoleTextAttribute(hConsole, 9);
printf("%d,\n",aux->key);fflush(stdout);
SetConsoleTextAttribute(hConsole, 15);
}
io_print(aux->RC,auxnill);
}
}
答案 0 :(得分:0)
在移植手术中有一个错误的指针错误......而我无法找到它,因为我没有多注意。我有:
void RB_transplant(struct node *aux,struct node *auxchild) //replace the subtree rooted at node aux with the subtree rooted at aux-LC or aux->RC
{
if (aux->P==nill) //if aux=root child becomes root
root=auxchild;
else if (aux==aux->P->LC) //if child is a LC
aux->P->LC=auxchild;
else aux->P->RC=auxchild; //if child is RC //connect grandparent's->RC with child
auxchild->P=aux->P; //connect child to point to parent
}
问题出在第5行,其中aux为=> auxhild ......问题解决了:)