求二叉树的先序遍历
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知一棵二叉树的中序遍历和后序遍历,求二叉树的先序遍历
Input
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的中序遍历序列,第二个字符串表示二叉树的后序遍历序列。
Output
输出二叉树的先序遍历序列
Sample Input
2 dbgeafc dgebfca lnixu linux
Sample Output
abdegcf xnliu
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
struct node
{
char x;
node *l,*r;
};
node *create(char *ord, char *la, int len)
{
node *rt = new node();
for(int i = 0; i < len; i++ )
{
if(la[len - 1] == ord[i])
{
rt->x = ord[i];
rt->l = create(ord, la, i);
rt->r = create(ord+i+1, la+i, len - i -1);
return rt;
}
}
return NULL;
}
void pre(node *rt)
{
if(rt)
{
printf("%c", rt->x);
pre(rt->l);
pre(rt->r);
}
}
int main()
{
int n;
scanf("%d", &n);
while(n--)
{
char ord[110], la[110];
scanf("%s%s", ord, la);
node *rt = create(ord, la, strlen(ord));
pre(rt);
printf("\n");
}
return 0;
}
771

被折叠的 条评论
为什么被折叠?



