#include <stdio.h>
#include <malloc.h>
typedef int KeyType;
typedef char InfoType[10];
typedef struct node
{
KeyType key;
InfoType data;
struct node *lchild,*rchild;
} BSTNode;
//在p所指向的二叉排序树中,插入值为k的节点
int InsertBST(BSTNode *&p,KeyType k)
{
if (p==NULL)
{
p=(BSTNode *)malloc(sizeof(BSTNode));
p->key=k;
p->lchild=p->rchild=NULL;
return 1;
}
else if (k==p->key)
return 0;
else if (k<p->key)
return InsertBST(p->lchild,k);
else
return InsertBST(p->rchild,k);
}
//由有n个元素的数组A,创建一个二叉排序树
BSTNode *CreateBST(KeyType A[],int n)
{
BSTNode *bt=NULL;
int i=0;
while (i<n)
{
InsertBST(bt,A[i]);
i++;
}
return bt;
}
void DispBST(BSTNode *bt)
{
if (bt!=NULL)
{
printf("%d",bt->key);
if (bt->lchild!=NULL || bt->rchild!=NULL)
{
printf("(");
DispBST(bt->lchild);
if (bt->rchild!=NULL) printf(",");
DispBST(bt->rchild);
printf(")");
}
}
}
BSTNode *SearchBST(BSTNode *bt,KeyType k)
{
if (bt==NULL || bt->key==k)
return bt;
if (k<bt->key)
return SearchBST(bt->lchild,k);
else
return SearchBST(bt->rchild,k);
}
BSTNode *SearchBST1(BSTNode *bt,KeyType k)
{
while (bt!=NULL)
{
if (k==bt->key)
return bt;
else if (k<bt->key)
bt=bt->lchild;
else
bt=bt->rchild;
}
return NULL;
}
void Delete1(BSTNode *p,BSTNode *&r)
{
BSTNode *q;
if (r->rchild!=NULL)
Delete1(p,r->rchild);
else
{
p->key=r->key;
q=r;
r=r->lchild;
free(q);
}
}
void Delete(BSTNode *&p)
{
BSTNode *q;
if (p->rchild==NULL)
{
q=p;
p=p->lchild;
free(q);
}
else if (p->lchild==NULL)
{
q=p;
p=p->rchild;
free(q);
}
else Delete1(p,p->lchild);
}
int DeleteBST(BSTNode *&bt, KeyType k)
{
if (bt==NULL)
return 0;
else
{
if (k<bt->key)
return DeleteBST(bt->lchild,k);
else if (k>bt->key)
return DeleteBST(bt->rchild,k);
else
{
Delete(bt);
return 1;
}
}
}
int main()
{
BSTNode *bt;
int n=12,x=46;
KeyType a[]= {25,18,46,2,53,39,32,4,74,67,60,11};
bt=CreateBST(a,n);
printf("BST:");
DispBST(bt);
printf("\n");
printf("删除%d结点\n",x);
if (SearchBST(bt,x)!=NULL)
{
DeleteBST(bt,x);
printf("BST:");
DispBST(bt);
printf("\n");
}
return 0;
}