题目链接:点击打开链接
数据结构实验之求二叉树后序遍历和层次遍历
Time Limit: 1000MS Memory limit: 65536K
题目描述
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。
输入
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
输出
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列
示例输入
2 abdegcf dbgeafc xnliu lnixu
示例输出
dgebfca abcdefg linux xnuli
提示
代码实现:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
struct Tree
{
char data;
Tree *lchild,*rchild;
};
char a[110],b[110];
///根据前序序列和中序序列求解树
Tree *Creat(int n,char a[],char b[])
{
Tree *p;
char *q;
if(n == 0)
return NULL;
p = new Tree;
p->data = a[0];///树根是当前元素在前序遍历中最先出现的元素
for(q = b;q != '\0';q++)///找出根节点在中序遍历中的位置,
///根左边的所有元素就是左子树,根右边的所有元素就是右子树
{
if(*q == a[0])
break;
}
int t;
t = q - b;
p->lchild = Creat(t,a + 1,b);///递归求解,将左子树和右子树分别看成一个二叉树
p->rchild = Creat(n - t - 1,a + t + 1,q + 1);
return p;
}
void Postorder(Tree *T)
{
if(T)
{
Postorder(T->lchild);
Postorder(T->rchild);
printf("%c",T->data);
}
}
/*
void Level(Tree *T)
{
int po = 0,pu = 0;
Tree *p[110];
p[pu++] = T;
while(pu > po)
{
if(p[po])
{
printf("%c",p[po]->data);
p[pu++] = p[po]->lchild;
p[pu++] = p[po]->rchild;
}
po++;
}
}*/
void Level(Tree *T)
{
int po = 0,pu = 0;
Tree *p[110];
p[pu++] = T;///根节点就是第一个元素
while(pu > po)
{
printf("%c",p[po]->data);///输出数组的第一个元素
if(p[po]->lchild)///如果左孩子不为空,进入数组
p[pu++] = p[po]->lchild;
if(p[po]->rchild)///如果右孩子不为空,进入数组
p[pu++] = p[po]->rchild;
po++;
}
}
int main()
{
int n;
while(~scanf("%d",&n))
{
while(n--)
{
Tree *T;
scanf("%s%s",a,b);
int len = strlen(a);
T = Creat(len,a,b);
Postorder(T);
printf("\n");
Level(T);
printf("\n");
}
}
return 0;
}