我在从 BST 中删除元素时遇到困难。此代码基于 Cormen 书中的算法。这是删除元素所需的两个函数:
el *TreeSuccessor(el *x)
{
el *y;
if (x->right != NULL){
return TreeMinimum(x->right);
}
y= x->p;
while (y != NULL && x == y->right){
x = y;
y = y->p;
}
return y;
}
void TreeDelete (el* &root, el *z, el* &y)
{
el *x;
if (z->left == NULL || z->right == NULL){
y=z;
}
else{
y=TreeSuccessor(z);
}
if(y->left != NULL){
x = y->left;
}
else{
x = y->right;
}
if (x!=NULL){
x->p = y->p;
}
if (y->p == NULL){
root=x;
}
else if (y == y->p->left){
y->p->left = x;
}
else{
y->p->right = x;
}
if (y!=z){
z->indeks = y->indeks;
strcpy(z->name,y->name);
strcpy(z->surname,y->surname);
}
}
这是负责调用函数的代码int main()
:
for (int i=0; i<n; i++)
{
File>>keyToSearch;
searchedLeave=TreeSearch(root,keyToSearch);
TreeDelete(root,searchedLeave,leaveToDelete);
delete leaveToDelete;
}
这是一个完整的程序http://pastebin.com/FgvWPzm9
删除期间程序崩溃。