BiSortTree.h //----------------------------------------------------头文件
#include<stdio.h>
#include<malloc.h>
typedef int KeyType;
typedef struct
{
KeyType key;
}DataType;
typedef struct node
{
DataType data;
struct node *leftChild;
struct node *rightChild;
}BiTreeNode;
int Search(BiTreeNode *root, DataType item)
{
BiTreeNode *p;
if(root != NULL)
{
p = root;
while(p != NULL)
{
if(p->data .key == item.key )
return 1;
if(item.key > p->data .key)
p = p->rightChild;
else
p = p->leftChild ;
}
}
return 0;
}
int Insert(BiTreeNode **root,DataType item)
{
BiTreeNode *current,*parent = NULL,*p;
current = *root;
while(current !=NULL)
{
if(current->data.key == item.key )
return 0;
parent = current;
if(current->data .key < item.key )
current = current->rightChild ;
else
current = current->leftChild ;
}
p = (BiTreeNode *)malloc(sizeof(BiTreeNode));
p->data = item ;
p->leftChild = NULL;
p->rightChild = NULL;
if(parent == NULL)
*root = p;
else if(item.key < parent->data .key )
parent->leftChild = p;
else
parent->rightChild = p;
return 1;
}
BiSortTree.cpp //---------------------------------------------------------------源文件
#include"BiSortTree.h"
void InTraverse(BiTreeNode *root)
{
if(root == NULL)
return;
if(root->leftChild != NULL)
InTraverse(root->leftChild);
printf("%d ",root->data.key);
if(root->rightChild != NULL)
InTraverse(root->rightChild);
}
void main()
{
DataType test[] = {4,5,7,2,1,9,8,11,3},x = {9};
int n = 9,i,s;
BiTreeNode *root = NULL;
for(i = 0;i<n;i++)
{
Insert(&root,test[i]);
}
InTraverse(root);
s = Search(root,x);
if(s == 1)
printf("\n数据元素%d存在!\n",x.key);
else
printf("\n数据元素不存在!\n");
}
结果:
1 2 3 4 5 7 8 9 11
数据元素9存在!