一、【实验目的】
1、掌握二叉排序树的基本概念
2、掌握二叉排序树的基本算法(查找算法、插入算法、删除算法)
2、理解并掌握二叉排序数查找的平均查找长度。
二、【实验内容】
1、已知一个个数为12的数据元素序列为{Dec,Feb,Nov,Oct,June,Sept,Aug,Apr,May, July,Jan,Mar},要求:
(1)按各数据元素的顺序(字母大小顺序)构造一棵二叉排序数,并中序打印排序结果。
(2)查找数据”Sept”是否存在。
三、【实验源代码】
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include<string.h>
typedef struct
{
char key[10];
}DataType;
typedef struct node
{
DataType data;
struct node *lchild;
struct node *rchild;
} BinaryTreeNode;
int Search(BinaryTreeNode *root, DataType x)
{
BinaryTreeNode *p;
if(root != NULL)
{
p = root;
while(p != NULL)
{
if(strcmp(p->data.key , x.key)==0) return 1;
if(strcmp(x.key , p->data.key)>0) p = p->rchild;
else p = p->lchild;
}
}
return 0;
}
int Insert(BinaryTreeNode **root, DataType x)
{
BinaryTreeNode *current, *parent = NULL, *p;
current = *root;
while(current != NULL)
{
if(strcmp(current->data.key , x.key)==0) return 0;
parent = current;
if(strcmp(current->data.key , x.key)<0) current = current->rchild;
else current = current->lchild;
}
p = (BinaryTreeNode *)malloc(sizeof(BinaryTreeNode));
if(p == NULL)
{
printf("空间不够!");
exit(1);
}
p->data = x;
p->lchild = NULL;
p->rchild = NULL;
if(parent == NULL) *root = p;
else if(strcmp(x.key , parent->data.key)<0)
parent->lchild = p;
else
parent->rchild = p;
return 1;
}
void InTraverse(BinaryTreeNode *root)
{
if(root == NULL) return;
if(root->lchild != NULL)
InTraverse(root->lchild);
printf("%s ", root->data.key);
if(root->rchild != NULL)
InTraverse(root->rchild);
}
int main(void)
{
DataType test[] = {"Dec","Feb","Nov","Oct","June","Sept","Aug","Apr","May","July","Jan","Mar"}, x = {"Sept"};
int n = 12, i;
BinaryTreeNode *root = NULL;
for(i = 0; i < n; i++)
{
Insert(&root, test[i]);
}
InTraverse(root);
if(Search(root, x))
printf("\n数据元素%s存在!", x.key);
else
printf("\n数据元素不存在!");
return 0;
}