# re: 二叉排序树的删除 回复 更多评论
2006-10-23 17:11 by
btree * DeleteBST(btree *b, ElemType x)
{
if (b)
if (x< b->data)
DeleteBST(b->lchild, x);
else if (x> b->data)
DeleteBST(b->rchild, x);
else if(b->lchild != null && b->rchild != null)
{
btree *temp = Min(b->rchild); // find the min key value in right child
DeleteBST(temp,temp->data);
}
else
{
if(b->rchild == null) b=b->lchild;
else if(b->lchild == null) b=b->rchild;
}
}
# re: 二叉排序树的删除 回复 更多评论
2007-10-15 12:48 by
二叉排序树删除节点
Status DeleteBST(BiTree &T, Keytype key,Bitree f) //引进f为T的父节点
{
if(!T) return FALSE;
else
{
if(EQ(key,T->data.key))
return Delete(T,f);
else
if(LT(key,T->data.key))
{
f = T;
return DeleteBST(T->lchild,key,f);
}
else
{
f = T;
return DeleteBST(T->rchile,key);
}
}
}
Status Delete(Bitree &p,Bitree f)
{
if(!p->rchild)
{
if(p==f->lchild)
f->lchild = p->lchild;
else
f->rchild = p->rchild;
free(p);
}
else if(!p->lchild)
{
if(f->lchild==p)
f->lchild = p->rchild;
else
f->rchild = p->rchild;
free(q);
}
else
{
BiTree q = p,s = p->rchild;
while(s->lchild)
{
q = s;
s = s->lchild; // 利用二叉排序树的前驱后继直观图帮助理解
} //探索p的直接前驱,最后得到其为s(s->lchild==NULL).
p->data = s->data; //覆盖,容易理解
if(q==p) // while未执行,有s=p->rchild,s覆盖p,s位置由s->rchild占据.
q->rchild = s->rchild;
else // 未执行else前有,q->lchild=s;
q->lchild = s->rchild;
free(s);
}
最后else部分亦可更改为:
else //利用直接前驱s替代p
{
BiTree q = p,s = p->lchild;
while(s->rchild)
{
q = s;
s = s->rchild;
} //探索p的直接前驱,最后得到其前驱为s(s->rchild==NULL).
p->data =s->data;
if(q==p)
q->lchild = s->lchild;
else
q->rchild = s->lchild;
free(s);
}
}