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>
char str1[100],str2[100];
int len;
int t;
struct node{
struct node *lchild,*rchild;
int date;
};
struct node*create(int len,char*str1,char*str2)
{
struct node *root;
root=(struct node*)malloc(sizeof(struct node));
if(len==0)
return NULL;
int i;
root->date=str2[len-1];//根节点
for(i=0;i<len;i++)
{
if(str1[i]==root->date)//str2中的位置
break;
}
root->lchild=create(i,str1,str2);//左子树,长度为i,i=0i=0时,返回NULL
root->rchild=create(len-i-1,str1+i+1,str2+i);//右子树,i为str1中根节点的位置,i右边即右子树,长度为len-(i+1),即len-i-1,str1是中序序列,i的位置是根节点,所以右子树从str1+i+i开始,str2是后序序列,所以i在str2中的位置不是根节点,而是右子树的第一个节点,所以从str2+i开始,str2的根节点在str2的最后,后序遍历顺序左-右-根。
return root;
};
void xian(struct node *root)
{
if(root)
{
printf("%c",root->date);
xian(root->lchild);
xian(root->rchild);
}
}
int main()
{
scanf("%d",&t);
for(t;t>0;t--)
{
scanf("%s",str1);
scanf("%s",str2);
len=strlen(str2);//后
struct node *root;
root=create(len,str1,str2);//中、后
xian(root);
printf("\n");
}
}