二叉排序树的建立、查找、插入和删除运算
#include<stdio.h>
#define ENDFLAG 0
typedef struct BSTNode{
int data;
struct BSTNode *lchild, *rchild;
}BSTNode, *BSTree;
BSTree T1,T2;
int SearchBST(BSTree T, int key){
if(!T) return 2;
if (key == T->data) return 1;
else if (key < T->data) return SearchBST(T->lchild, key);
else return SearchBST(T->rchild, key);
}
void InsertBST(BSTree &T, int e){
BSTree S;
if (!T){
S = new BSTNode;
S->data = e;
S->lchild = S->rchild = NULL;
T = S;
}
else if (e < T->data)
InsertBST(T->lchild, e);
else if (e > T->data)
InsertBST(T->rchild, e);
}
void DeleteBST(BSTree &T, int key){
BSTree p,f,q,s;
p = T; f = NULL;
while (p){
if(p->data == key) break;
f = p;
if (p->data > key) p = p->lchild;
else p = p->rchild;
}
if (!p) return;
q = p;
if ((p->lchild) && (p->rchild)){
s = p->lchild;
while (s->rchild){
q = s;
s = s->rchild;
}
p->data = s->data;
if (q != p) q->rchild = s->lchild;
else q->lchild = s->lchild;
delete s;
return;
}
else if (!p->rchild) p = p->lchild;
else if (!p->lchild) p = p->rchild;
if (!f) T = p;
else if (q == f->lchild) f->lchild = p;
else f->rchild = p;
delete q;
}
void order(BSTree T){
if (T == NULL) {
return;
}
order(T->lchild);
printf("%d ", T->data);
order(T->rchild);
}
int main(){
int i,j;
int a[7] = {5,4,2,1,7,3,6};
int b[7] = {1,2,3,4,5,6,7};
for (i = 0; i < 7; i++) {
InsertBST(T1,a[i]);
InsertBST(T2,b[i]);
}
printf("请输入要在第一组数据中查找的数:");
scanf("%d",&i);
j=SearchBST(T1,i);
if(j==1)
printf("找到了!");
else
printf("未找到!");
printf("\n");
printf("请输入要在第二组数据中查找的数:");
scanf("%d",&i);
j=SearchBST(T2,i);
if(j==1)
printf("找到了!");
else
printf("未找到!");
printf("\n");
printf("中序遍历二叉排序树:\n");
order(T1);
printf("\n");
order(T2);
printf("\n");
printf("请输入要删除的数:");
scanf("%d",&i);
printf("删除%d后,中序遍历二叉排序树:\n",i);
DeleteBST(T1,i);
order(T1);
printf("\n");
DeleteBST(T2,i);
order(T2);
printf("\n");
return 0;
}