数据结构实验之求二叉树后序遍历和层次遍历

来源:互联网 发布:仿站长之家网站源码 编辑:程序博客网 时间:2024/05/17 04:23

数据结构实验之求二叉树后序遍历和层次遍历

Time Limit: 1000MS Memory limit: 65536K

题目描述

 已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。

输入

 输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。

输出

每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列

示例输入

2abdegcfdbgeafcxnliulnixu

示例输出

dgebfcaabcdefglinuxxnuli

提示

 

来源

ma6174

示例程序

 


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int L;  
struct node 
{
int data;
struct node *rchild;
struct node *lchild;
};
struct node *creat(int n,char a[],char b[])
{
struct node *root;
char *p;
if(n==0)
{
return NULL; //返回上一层创建二叉树函数
}
root = (struct node *)malloc(sizeof(struct node));
root->data = a[0];
for(p=b;p!='\0';p++)//在b中找到和a[0]相同的元素,跳出循环
{
if(*p==a[0])
{
break;
}
}
int t=p-b; //记录b中第几个字符与a【0】相同,传参给创建二叉树函数
root->lchild = creat(t,a+1,b);
root->rchild = creat(n-1-t,a+t+1,p+1);
return root;
}
void final(struct node *root)
{
if(root)  
    {  
         final(root->lchild);  
         final(root->rchild);  
         printf("%c",root->data);  
    }  
}
void Exbition(struct node *root)  //层次遍历输出
{       
int in,out;
in = out = 0;
struct node *p[100]; //保存数据,从根节点到叶子的数据分层保存下来
p[in++] = root; //保存根上的元素
while(out<in)
{
if(p[out]) //如果访问的结点不为空
{
printf("%c",p[out]->data ); //输出访问的结点元素
p[in++] = p[out]->lchild; //将访问结点的左子树的地址传给下一个输出的节点元素
p[in++] = p[out]->rchild;//将访问结点的右子树的地址传给下一个输出的节点元素
}
out++;
}
}
int main()
{
char a[55],b[55];
int n,m;
struct node *root;
while(scanf("%d",&n)!=EOF)
{
L=0;
while(n--)
{
scanf("%s%s",a,b);
int k=strlen(a);//记录字符串长度,传参数给创建二叉树。
root = creat(k,a,b);
final(root);//后序遍历输出
printf("\n");
Exbition(root);//层次遍历输出
printf("\n");
}
}
return 0;
}




0 0
原创粉丝点击