用二叉树实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 50//定义字符串长度
//定义二叉树链式结构
typedef struct BitSortNode
{
char *data; //数据域
struct BitSortNode *lchild;//左子树
struct BitSortNode *rchild;//右子树
}BitSortNode,*BiSortTree;
//递归实现二叉排序树插入
int InsertBiSortTree(BiSortTree *bst,char* item)
{
if(*bst==NULL)
{
//把按照item元素生成的新结点链接到已找到的插入位置
BiSortTree p;
p=(BiSortTree)malloc(sizeof(BitSortNode));
if(p==NULL)
{
printf("申请二叉排序树内存出错\n");
return 0;
}
p->data=(char*)malloc(sizeof(char)*(strlen(item)+1));
if(p->data==NULL)
{
printf("申请内存出错\n");
return 0;
}
strcpy(p->data,item);//拷贝数据
p->data[strlen(item)]='\0';//末尾置结束符号
p->lchild=p->rchild=NULL;
(*bst)=p;
}
else if(strcmp(item,(*bst)->data)==0) return 1;//相等直接返回,不插入
//else if(strcmp(item,(*bst)->data)< 0) //向左子树中插入元素
//InsertBiSortTree((*bst)->lchild,item);
else //向右子树中插入元素
InsertBiSortTree(&(*bst)->rchild,item);
return 1;
}
//创建二叉排序树
int CreateBiSortTree(BiSortTree *bst)
{
char *s,*p;
int i=0,flag=0;
int max=N;
s=(char*)malloc(sizeof(char)*N);
if(s==NULL)
return 0;
printf("录入数据,双冒号结束\n");
while(1)
{
while(i<max)//输入个数不超过定义长度
{
s[i]=getchar();
if(s[i]==':')//如果是:
{
if(flag==1)//如果是连续:,终止输入
{
s[i+1]='\0';//置结束符号
break;
}
else
flag=1;//否则置标志
}
else
flag=0;//其余字符不置标志
i++;
}
if(i >=max)//如果长度超过定义,扩充
{
s=(char*)realloc(s,sizeof(char)*(max/N+1)*N);//变成多个N的长度
if(s==NULL)
return 0;
max+=N;//累加限定长度
}
else
break;
}
//printf("%s\n",s);
p=strtok(s,":");//分解冒号
while(p!=NULL)
{
if(InsertBiSortTree(bst,p)==0)
return 0;
//printf("%s\n",p);
p=strtok(NULL,":");
}
free(s);
return 1;
}
//递归实现中序遍历
void InorderBST(BiSortTree bst)
{
if(bst!=NULL)
{
//如果不为空
InorderBST(bst->lchild); //递归遍历左子树
printf("%s:",bst->data); //输出根节点值
InorderBST(bst->rchild); //递归遍历右子树
}
}
//二叉树释放内存
void FreeBiSortTree(BiSortTree bst)
{
if(bst!=NULL)
{
if(bst->lchild!=NULL)
FreeBiSortTree(bst->lchild);
if(bst->rchild!=NULL)
FreeBiSortTree(bst->rchild);
free(bst);
}
}
int main(void)
{
BiSortTree bst=NULL;
//建立二叉排序树
if(CreateBiSortTree(&bst)==0)
return 1;
//输出
InorderBST(bst);
printf(":\n");
//释放空间
FreeBiSortTree(bst);
return 0;
}
温馨提示:答案为网友推荐,仅供参考