局部函数的源码:
void DeleteBST(BiNode<T> *&BST)//删除二叉搜索树中的结点
{
BiNode<T> *temp;
temp=BST;
temp=temp->rchild;
}
为什么在函数内部我自己设置的temp->rchild已经等于NULL了,但是跳出函数之后他还是返回到原来的样子呢(原来:temp—>rchild非空)?如何改进局部函数才能在返回主函数时BST被rchild取代?
BST = temp->rchild
BST=BST->rchild
我这个temp=BST是需要保留的,上面我的代码时缩略了很多的,以下才是局部函数的原码:
(我设定的BST->data=6,BST->rchild->data=7)
(pointer指向的是BST自己)
所以只执行了函数中的这几步,在下列编码中我用************标记
void DeleteBST(BiNode<T> *pointer,BiNode<T> *&BST)//删除二叉搜索树中的结点
{
BiNode<T> *rtemp,*temp,*tempparent;
temp=BST;
tempparent=NULL;
if(!pointer)
{
return;
}
while(pointer!=temp)//寻找二叉搜索树中数值相同的点
{
if(pointer->data<temp->data)
{
temp=temp->lchild;
}
if(pointer->data>temp->data)
{
temp=temp->rchild;
}
if(pointer->data==temp->data)
{
tempparent=temp->Parent(temp,BST);
pointer=temp;
}
}
/*if(tempparent==NULL)
{
BST=NULL;
}*/
if(temp->lchild==NULL&&temp->rchild==NULL && tempparent)
{
if(temp->data>tempparent->data)
{
delete temp;
tempparent->rchild=NULL;//改........................
}
else
{
delete temp;
tempparent->lchild=NULL;
}
delete temp;
}
else
{
if(!temp->lchild&&temp->rchild)************
{
temp=temp->rchild;
}
if(!temp->rchild&&temp->lchild)
{
temp=temp->lchild;
}
if(temp->lchild&&temp->rchild)
{
rtemp=temp->rchild;
Rdeletemin(rtemp);//求出右子树中最小的叶子;
rtemp->lchild=temp->lchild;
temp->lchild=NULL;
temp=temp->rchild;
}
}
}
void DeleteBST(BiNode<T> *pointer,BiNode<T> *&BST)
{
BiNode<T> *rtemp,*temp,*tempparent;
BiNode<T> *head = pointer;// 备份pointer
temp=BST;
/*下面的不动*/
tempparent=NULL;
...
pointer = head; //在结束前,将pointer返回开始
}