发布时间:2019-07-29 16:14:02
#include <stdio.h>
#include <stdlib.h>
#define Max 10
typedef char KeyType;
typedef struct
{
KeyType key[Max];
}ElemType;
typedef struct node{
ElemType data;
struct node *lchild,*rchild;
}BinaryTreeNode;
typedef BinaryTreeNode *BiTree;
int InsertBiTree(BinaryTreeNode **root, ElemType x)
{
BinaryTreeNode *current,*parent=NULL,*p;
current=*root;
while(current!=NULL)
{
if(current->data.key==x.key)
return 0;
parent=current;
if(current->data.key<x.key)
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(x.key<parent->data.key)
parent->lchild=p;
else
parent->rchild=p;
return 1;
}
//查找算法
int BiTreeSearch(BinaryTreeNode *root, ElemType x)
{
BinaryTreeNode *current;
if(root != NULL)
{
current=root;
while(current!= NULL)
{
if(current->data.key==x.key)
return 1;
if(x.key>current->data.key)
current=current->rchild;
else
current=current->lchild;
}
}
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()
{
ElemType test[] = {"Dec","Feb","Nov","Oct","June","Sept","Aug","Apr","May","July","Jan","Mar"}, t= {"July"};
int n = 12, i, s;
BinaryTreeNode *root = NULL;
for(i = 0; i < n; i++)
{
InsertBiTree(&root, test[i]);
}
InTraverse(root);
printf("\n");
s=BiTreeSearch(root, t);
if(s==1)
printf("查找数据%s存在!\n", t.key);
else
printf("查找数据%s不存在!\n");
return 0;
}