您的位置:首页 > 产品设计 > UI/UE

二叉树及按层遍历的算法实现

2011-09-02 20:25 411 查看
/******************************
//  建立二叉树
//  及按层遍历的算法实现
******************************/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define size 256

typedef char datatype;

typedef struct node
{
datatype data;
struct node *lchild;
struct node *rchild;
}*root,treenode;

void init(root *t)
{
(*t) = NULL;
}

void input(char *pre_str, char *in_str )
{
printf("please input the pre_order string:\n");
gets(pre_str);
printf("please input the in_order string:\n");
gets(in_str);
if(strlen(pre_str) != strlen(in_str)){
puts("different string !!!");
}
}

void build(char *pre_str,char *in_str,int len,root *t)
{
if(pre_str == NULL || in_str == NULL)
return ;

(*t) = (root)malloc(sizeof(treenode));
(*t)->data=*pre_str;
(*t)->lchild=NULL;
(*t)->rchild=NULL;

if(len == 1)
return ;

char *first=in_str;
char *move=in_str;
int tmp_len=0;

while((*pre_str) != *move){

if(pre_str == NULL || move == NULL)
return ;
tmp_len++;

if(tmp_len>len)
break;
move++;
}

int l_len,r_len;
l_len = (int)(move-first);
r_len = (len-l_len-1);

if(l_len > 0)
build(pre_str+1,in_str,l_len,&((*t)->lchild));
if(r_len > 0)
build(pre_str+1+l_len,in_str+1+l_len,r_len,&((*t)->rchild));

}

void travel_pre(root t)
{
if(t == NULL)
return ;
printf("%c ",t->data);
travel_pre(t->lchild);
travel_pre(t->rchild);
}

void travel_in(root t)
{
if(t == NULL)
return ;
travel_in(t->lchild);
printf("%c ",t->data);
travel_in(t->rchild);
}

void travel_post(root t)
{
if(t == NULL)
return ;
travel_post(t->lchild);
travel_post(t->rchild);
printf("%c ",t->data);
}

void travel_level(root t)
{
root quen[size];
int front=-1;
int rear=-1;
rear++;
quen[rear] = t;

while(front != rear){

root tmp;
front=(front+1) % size;
tmp=quen[front];
printf("%c ",tmp->data);

if(tmp->lchild != NULL){
rear = (rear+1)%size;
quen[rear]=tmp->lchild;
}

if(tmp->rchild != NULL){
rear = (rear+1)%size;
quen[rear]=tmp->rchild;
}

}

}

int main(void)
{
root t;
init(&t);
int len;
char pre_str[size];
char in_str[size];

input(pre_str,in_str);
len = strlen(pre_str);

build(pre_str,in_str,len,&t);

printf("the pre_order is: \n");
travel_pre(t);
printf("\n");

printf("the in_order is:\n");
travel_in(t);
printf("\n");

printf("the post_order is:\n");
travel_post(t);
printf("\n");

printf("the level_order is:\n");
travel_level(t);

printf("\n");
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐