您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之求二叉树后序遍历和层次遍历(简单版)

2016-08-22 20:53 274 查看
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct tnode
{
char data;
tnode *lc,*rc;
}*tree;

void build(tree &t,char *he,char *mid,int len)  //数组用字符来代替
{
if(len==0) t=NULL;  //递归停止条件
else
{
int k=0;
int n=strlen(mid);
for(;k<n;k++)      //寻找根节点
{
if(mid[k]==*he)
break;
}
t=new(tnode);
t->data=*he;

build(t->lc,he+1,mid,k);     //t->lc;  递归左子树

build(t->rc,he+k+1,mid+k+1,len-(k+1));   //t->rc;  递归右子树
}
}

void last(tree &t)  //后序遍历
{
if(t)
{
last(t->lc);
last(t->rc);
printf("%c",t->data);
}
}

void ceng(tree &t)     //层序遍历
{
tnode *p[1000];
int rear=0,front=0;
if(t)
p[rear++]=t;
while(rear>front)
{
t=p[front++];
printf("%c",t->data);
if(t->lc) p[rear++]=t->lc;
if(t->rc) p[rear++]=t->rc;
}
}

int main()
{
int n;
char he[55],mid[55];
tree t;
scanf("%d",&n);
while(n--)
{
scanf("%s %s",he,mid);
int len=strlen(he);
build(t,he,mid,len);
last(t);
printf("\n");
ceng(t);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  代码 二叉树