第1个回答 2013-11-19
//与他人分享自己的程序,开源
#include <stdio.h>
#include <stdlib.h>
typedef int KeyType;
typedef struct node
{
KeyType key ;
struct node *lchild,*rchild;
}BSTNode, *BSTree;
void InsertBST(BSTree *bst, KeyType key)
{
BSTree s;
if (*bst == NULL)
{
s=(BSTree)malloc(sizeof(BSTNode));
s-> key=key;
s->lchild=NULL;
s->rchild=NULL;
*bst=s;
}
else
if (key < (*bst)->key)
InsertBST(&((*bst)->lchild), key);
else
if (key > (*bst)->key)
InsertBST(&((*bst)->rchild), key);
}
BSTNode * DelBST(BSTree t, KeyType k)
{
BSTNode *p, *f,*s ,*q;
p=t;
f=NULL;
while(p)
{
if(p->key==k ) break;
f=p;
if(p->key>k)
p=p->lchild;
else
p=p->rchild;
}
if(p==NULL) return NULL;
if(p->lchild==NULL)
{
if(f==NULL)
t=p->rchild;
else
if(f->lchild==p)
f->lchild=p->rchild ;
else
f->rchild=p->rchild ;
free(p);
}
else
{
q=p;
s=p->lchild;
while(s->rchild)
{
q=s;
s=s->rchild;
}
if(q==p)
q->lchild=s->lchild ;
else
q->rchild=s->lchild;
p->key=s->key;
free(s);
}
return t;
}
void CreateBST(BSTree *bst)
{
int ENDKEY=0,key;
*bst=NULL;
scanf("%d", &key);
while (key!=ENDKEY)
{
InsertBST(bst, key);
scanf("%d", &key);
}
}
void PreOrder(BSTree root)
{
if (root!=NULL)
{
printf("%d ",root->key);
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
void main()
{
BSTree T;
int k;
printf("建立二叉排序树,请输入序列以0结束输入:\n");
CreateBST(&T);
printf("先序遍历输出序列为:");
PreOrder(T);
printf("\n输入你要删除的数:");
scanf("%d",&k);
T=DelBST(T,k);
if(T==NULL)
printf("无此数");
else
printf("先序遍历输出这个序列为:");
PreOrder(T);
printf("\n");
}