/*(5)输入互不相同的一组整数,构造一棵二叉排序树,要求:
① 按递减有序的顺序输出;
② 输入一个整数,查找该整数是否在该二叉排序树中,查找成功返回1,否则返回0;
③ 在②中,若查找成功,则将该结点从二叉排序树中删除。
*/
#include<stdio.h>
#include <time.h>
#include <stdlib.h>
#define MAX 100
#define N 5
typedef struct BiTNode{
int data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct SqStack{
BiTree *base;
int top;
int stacksize;
}SqStack;
void CreatBfs(BiTree &bst,int num[MAX],int n){//构造一课二叉排序树
BiTNode *p,*f,*s;
if(n<1){
bst=NULL;
return ;
}
bst=(BiTree)malloc(sizeof(BiTNode));
bst->data=num[0];
bst->lchild=bst->rchild=NULL;
for(int i=1;i<n;i++){
p=bst;f=NULL;
while(p&&(p->data)!=num[i]){
if(p->data<num[i]){
f=p;
p=p->lchild;
}
else {
f=p;
p=p->rchild;
}
}
if(!p){
s=(BiTree)malloc(sizeof(BiTNode));
s->data=num[i];
s->lchild=s->rchild=NULL;
}
if(num[i]>f->data)
f->lchild=s;
else f->rchild=s;
}
}
void Output(BiTree &bst){//递归输出
if(bst){
Output(bst->lchild);
printf(“%5d”,bst->data);
Output(bst->rchild);
}
}
int Search(BiTree bst,int key){
int count;
int n=100;
while(bst){
if(bst->data==key)
return 1;
else{
if(bst->data>key)
return Search(bst->rchild,key);
else
return Search (bst->lchild,key);
}
count++;
}
if(count>n)
return 0;
}
void Delet(BiTree &p){
BiTree q,f,s;
if(!p->lchild){
q=p;
p=p->rchild;
free(q);
}
else if (!p->rchild){
q=p;
p=p->lchild;
free(q);
}
else {
q=p;
while(s->rchild){
q=s;
s=s->rchild;
}
p->data=s->data;
if(p!=q){
q->rchild=s->lchild;
}
else q->lchild=s->lchild;
free(s);
}
}
int DeletBst(BiTree &bst,int key){
if(!bst)
return 0;
else{
if(bst->data==key)
Delet(bst);
else if(bst->data<key)
return DeletBst(bst->lchild,key);
else return DeletBst(bst->rchild,key);
}
}
int main(){
SqStack S;
int count=0;
int key;
int num[MAX],i,n;
BiTree bst;
printf(“请输入这组数的个数:”);
scanf(“%d”,&n);
printf(“请随机输入%d个随机整数:”,n);
for(int i;i<n;i++){
scanf(“%d”,&num[i]);
}
CreatBfs(bst,num,n);
Output(bst);
printf(“\n”);
printf(“输入要查找的关键字:”);
scanf(“%d”,&key);
i=Search(bst,key);
printf(“%d\n”,i);
printf(“输入要删除的关键字:”);
scanf(“%d”,&key);
DeletBst(bst,key);
printf(“\n”);
Output(bst);
return 0;
}