Problem Description
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历和层序遍历。
Input
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。
Output
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列。
Example Input
2
abdegcf
dbgeafc
xnliu
lnixu
Example Output
dgebfca
abcdefg
linux
xnuli
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
char pre[55],in[55];
struct Node
{
int data;
struct Node *lchild;
struct Node *rchild;
};
//返回构造的二叉树的根
Node *CreatTree(char *pre,char *in,int n)
{
Node *p;
char *q;
int k;
if(n <= 0)
return NULL;
p = (Node *)malloc(sizeof(Node));
p->data = *pre;//i
for(q=in;q<in+n;q++)
{
if(*q == *pre)
break;
}
k = q-in;
p->lchild = CreatTree(pre+1,in,k);
p->rchild = CreatTree(pre+k+1,q+1,n-k-1);
return p;
}
//后序遍历
void PostOrder(Node *b)
{
if(b!=NULL)
{
PostOrder(b->lchild);
PostOrder(b->rchild);
printf("%c",b->data);
}
}
//层次遍历(用队列完成)
void levelOrder(Node *b)
{
queue<struct Node *> Q;
Q.push(b); //现将节点入队
while(!Q.empty()) //队列不为空时循环
{
Node *t;
t = Q.front(); //队头元素
if(t)
{
Q.push(t->lchild); //向队列中添加元素t->lchild(顺序的将树的节点一个个入队)
Q.push(t->rchild); //向队列中添加元素t->rchild
printf("%c",t->data); //输出当前的节点
}
Q.pop(); //从队列中取出并删除元素
}
}
int main()
{
int T;
int len;
scanf("%d",&T);
while(T--)
{
scanf("%s",pre);
len = strlen(pre);
scanf("%s",in);
Node *b = CreatTree(pre,in,len);
//后序遍历
PostOrder(b);
printf("\n");
//层序遍历
levelOrder(b);
printf("\n");
}
return 0;
}