#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int KeyType;
typedef int ElemType;
typedef struct bstnode
{ KeyType key;
ElemType data;
struct bstnode *leftchild,*rightchild;
}BSTNode;
int BSTInsert(BSTNode * &bt,KeyType k)
{ BSTNode *f,*p=bt;
while(p!=NULL)
{ if(p->key==k)
return 0;
f=p;
if(k<p->key)
p=p->leftchild;
else
p=p->rightchild;
}
p=(BSTNode * )malloc(sizeof(BSTNode));
p->key=k;
p->leftchild=p->rightchild=NULL;
if(bt==NULL)
bt=p;
else if (k<f->key)
f->leftchild=p;
else
f->rightchild=p;
return 1;
}
void CreateBST(BSTNode * &bt,KeyType a[],int n)
{ bt=NULL;
int i=0;
while(i<n)
{ BSTInsert(bt,a[i]);
i++;
}
}
void DestroyBST(BSTNode * &bt)
{ if(bt!=NULL)
{ DestroyBST(bt->leftchild);
DestroyBST(bt->rightchild);
free(bt);
}
}
void DispBST(BSTNode *bt)
{ if (bt!=NULL)
{ printf("%d",bt->key);
if (bt->leftchild!=NULL || bt->rightchild!=NULL)
{ printf("(");
DispBST(bt->leftchild);
if (bt->rightchild!=NULL)
printf(",");
DispBST(bt->rightchild);
printf(")");
}
}
}
BSTSearch(BSTNode *bt,KeyType k)
{ BSTNode *p=bt;
while (p!=NULL)
{ if (p->key == k)
{printf("\n\t与%d比较,相等\n",p->key);
return 1;
}
else if (k < p->key)
{printf("\n\t与%d比较,不相等\n",p->key);
p=p->leftchild;
}
else {printf("\n\t与%d比较,不相等\n",p->key);
p=p->rightchild;
}
}
return 0;
}
int main()
{ KeyType a[]={40,28,6,72,100,3,54,15,80,91},b,d,i,n=10;
BSTNode *bt;
CreateBST(bt,a,n);
printf("初始序列:");
for(i=0; i<n; i++)
{d=a[i];printf(" %d ",d);
}
printf("\n");
printf("该二叉排序树的括号表示法:");
DispBST(bt);
printf("\n");
printf("\n查找30:\n");
b=BSTSearch(bt,30);
if(b==0) printf("\n查找30失败\n");
else printf("\n查找30成功\n");
printf("\n查找80:\n");
b=BSTSearch(bt,80);
if(b==0) printf("\n查找80失败\n");
else printf("\n查找80成功\n");
return 0;
}