#include <stdio.h>#include <stdlib.h>#define ENDKEY 0typedefintKeyType;
typedefstructnode{
KeyTypekey ; structnode*lchild,*rchild;}BSTNode, *BSTree;
voidInsertBST(BSTree*bst, KeyTypekey)
{
BSTrees;
if (*bst==NULL) {
s=(BSTree)malloc(sizeof(BSTNode));s->key=key;
s->lchild=NULL;
s->rchild=NULL;
*bst=s;
}
elseif (key< (*bst)->key)
InsertBST(&((*bst)->lchild), key);elseif (key> (*bst)->key)
InsertBST(&((*bst)->rchild), key); }
voidCreateBST(BSTree*bst)
{
KeyTypekey;
*bst=NULL;
scanf("%d", &key);
while (key!=ENDKEY) {
InsertBST(bst, key);
scanf("%d", &key);
}
}
voidPreOrder(BSTreeroot)
{
if (root!=NULL)
{
PreOrder(root->lchild); printf("%d ",root->key); PreOrder(root->rchild); }
}
BSTreeSearchBST(BSTreebst, KeyTypekey)
{
BSTreeq;
q=bst;
while(q)
{
if (q->key==key)
returnq; if (q->key>key)
q=q->lchild; elseq=q->rchild; }
returnNULL; }BSTNode*DelBST(BSTreet, KeyTypek) {
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;
elsep=p->rchild;
}
if(p==NULL) returnt; if(p->lchild==NULL) {
if(f==NULL)
t=p->rchild; elseif(f->lchild==p) f->lchild=p->rchild ; elsef->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 ; elseq->rchild=s->lchild;
p->key=s->key; free(s);
}
returnt;
} voidmain()
{
BSTreeT;
intk;
BSTreeresult;
printf("建立二叉排序树,请输入序列:\n");
CreateBST(&T);
printf("中序遍历输出序列为:");
PreOrder(T);
printf("\n请输入要查找的元素:");
fflush(stdin);
scanf("%d",&k);
result=SearchBST(T,k);
if (result!=NULL)
printf("要查找的元素为%d\n",result->key);
elseprintf("未找到!\n");
result=DelBST(T,k);
PreOrder(result);
}