数据结构实验八 动态查找算法的实现

一、【实验目的】
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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值