原题链接:oj1489
求二叉树的先序遍历
Description
已知一棵二叉树的中序遍历和后序遍历,求二叉树的先序遍历
Input
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的中序遍历序列,第二个字符串表示二叉树的后序遍历序列。
Output
输出二叉树的先序遍历序列
Sample
Input
2
dbgeafc
dgebfca
lnixu
linux
Output
abdegcf
xnliu
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
struct node
{
int data;
struct node *l,*r;// l为指向左子树,r指向右子树
};
/*将先序序列分为 根 左子树 右子树
根直接存到结构体中
左子树和右子树继续调用该函数->分成 根 左子树 右子树
*/
struct node *build(char *mid,char *beh,int len)
{
struct node *st;
if(len<=0)
{
return NULL;
}
else
{
int i;
st=(struct node *)malloc(sizeof(struct node));
st->data=beh[len-1];//存入
for(i=0;i<len;i++)
{
if(mid[i]==beh[len-1])//找到根的位置
{
break;
}
}
st->l=build(mid,beh,i);//左子树
st->r=build(mid+1+i,beh+i,len-i-1);//右子树
}
return st;
}
void pull(struct node *st) //输出**先序**遍历序列
{
if(st!=NULL)
{
printf("%c",st->data);
pull(st->l);
pull(st->r);
}
}
int main()
{
int t,len;
char mid[55],beh[55];
scanf("%d",&t);
while(t--)
{
struct node *st;
scanf("%s%s",mid,beh);
len=strlen(mid);
st=build(mid,beh,len);
pull(st);
printf("\n");
}
return 0;
}