一、实验教学的内容或要求
1.编写函数,建立有序表,采用折半查找实现某一已知的关键字的查找(采用顺序表存储结构)
2.编写函数,随机产生一组关键字,利用二叉排序树的插入算法建立二叉排序树
3.编写函数,在以上二叉排序树中删除某一指定关键字元素
4.编写一个主函数,在主函数中设计一个简单的菜单,分别调试上述算法
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <time.h>
#define LIST 20
typedef int KeyType;
typedef struct Node
{
KeyType key;
struct Node*Lchild, *Rchild;
}NodeType ,*BStree;
//二分查找
int BinSrch(int a[],int k,int n)
{
int left=1, right=n;
while (left <= right)
{
int mid = (left+right) / 2;
if (k == a[mid])
return mid;
else if (k < a[mid]) right = mid - 1;
else left = mid + 1;
}
return 0;
}
void BinaryFind()
{
int a[LIST]; int n, i, key, j;
printf("请输入数组的长度: ");
scanf("%d",&n);
printf("请输入一组数:");
for (i = 1; i <= n; i++)
scanf("%d",&a[i]);
printf("请输入你要找的数:") ;
scanf("%d", &key);
j = BinSrch(a, key, n);
if (j == 0)
printf("抱歉没有该数");
else printf("找到了,此数为: %d", a[j]);
}
void Insert(BStree *b,KeyType key)
{
BStree s;
if (*b == NULL)
{
s = (BStree)malloc(sizeof(NodeType));
s->key = key;
s->Lchild = NULL;
s->Rchild = NULL;
*b = s;
}
else if (key < (*b)->key)
Insert(&((*b)->Lchild), key);
else if (key>(*b)->key)
Insert(&((*b)->Rchild), key);
}
void CreateBST(BStree*b)
{
KeyType key;
*b = NULL;
int i;
srand((unsigned)time(NULL));//初始化随机数
for (i = 0; i < 8;i++)
{
key = (rand() % 10 + 1);
printf("%d ",key);
Insert(b,key);
}
}
void PreOrder(BStree root)
{
if (root != NULL)
{
printf("%d ", root->key);
PreOrder(root->Lchild);
PreOrder(root->Rchild);
}
}
NodeType *Delete(BStree t,KeyType k)
{
NodeType *p, *f, *s, *q;
p = t;
f = NULL;
while (p)
{
if (p->key==k)
break;
f = p;
if (p->key > k)
p = p->Rchild;
else p = p->Rchild;
}
if (p==NULL)
return t;
if (p->Lchild == NULL)
{
if (f == NULL)
t = p->Rchild;
else
if (f->Lchild == p)
f->Lchild = p->Rchild;
else
f->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->Rchild;
else
q->Rchild = s->Lchild;
p->key = s->key;
free(s);
}
return t;
}
void menu()
{
printf("\t\t\t\t\t\t\t主菜单页面\n");
printf("\t\t\t输入1 建立有序表,采用折半查找实现某一已知的关键字的查找\n");
printf("\t\t\t输入2 随机产生一组关键字, 利用二叉排序树的插入算法建立二叉排序树\n");
printf("\t\t\t输入3 在以上二叉排序树中删除某一指定关键字元素\n");
printf("\t\t\t输入4 结束\n");
}
int main()
{
KeyType k;
int c = 0;
int flag = 1;
while (flag)
{
menu();
printf("\n请输入相对应的选项:");
scanf("%d",&c);
switch (c)
{
case 1:
BinaryFind();
printf("\n");
break;
case 2:
BStree T;
printf("输入二叉树序列:");
CreateBST(&T);
printf("\n");
printf("遍历结果如下:");
PreOrder(T);
printf("\n");
break;
case 3:
BStree result;
printf("输入二叉树序列:");
CreateBST(&T);
printf("\n");
printf("初始遍历结果如下:");
PreOrder(T);
printf("\n请输入删除的元素:");
scanf("%d",&k);
printf("删除之后遍历结果如下:");
result = Delete(T,k);
PreOrder(result);
printf("\n");
break;
case 4:
printf("退出\n");
flag = 0;
}
}
system("pause");
return 0;
}