**数据结构实验之求二叉树后序遍历和层次遍历**
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。
输入
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
输出
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列
示例输入
2
abdegcf
dbgeafc
xnliu
lnixu
示例输出
dgebfca
abcdefg
linux
xnuli
代码::
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
node *l,*r;
}*q[110];
struct node *creat(char *s,char *a,int len)
{
if(len <= 0)
return NULL;
node *head = new node;
head->l = NULL;
head->r = NULL;
head->data = *s;
int p = strchr(a,*s) - a;
head->l = creat(s+1,a,p);
head->r = creat(s+p+1,a+1+p,len-p-1);
return head;
}
void post(node *head)
{
if(head)
{
post(head->l);
post(head->r);
printf("%c",head->data);
}
}
void cenci(node *head)
{
int e = 0;
int s = 0;
q[s++] = head;
while(s > e)
{
head = q[e++];
printf("%c",head->data);
if(head->l)
q[s++] = head->l;
if(head->r)
q[s++] = head->r;
}
}
int main()
{
std::ios::sync_with_stdio(false);
int n;
char s[51],a[51];
while(cin>>n)
{
while(n--)
{
cin>>s>>a;
int len = strlen(s);
node *head = creat(s,a,len);
post(head);
printf("\n");
cenci(head);
printf("\n");
}
}
return 0;
}