Problem Description
已知一棵二叉树的中序遍历和后序遍历,求二叉树的先序遍历
Input
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的中序遍历序列,第二个字符串表示二叉树的后序遍历序列。
Output
输出二叉树的先序遍历序列
Sample Input
2
dbgeafc
dgebfca
lnixu
linux
Sample Output
abdegcf
xnliu
代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
char data;
struct node *left,*right;
};
struct node *creattree(int n,char *str1,char *str2)//二叉树的重建与后续遍历输出
{
struct node *root;
int i;
if(n==0)
return NULL;
root=(struct node *)malloc(sizeof(struct node));
root->data=str1[n-1];//找到根节点,根节点为str1(先序序列)的第一个
for(i=0; i<n; i++) //找到str2(中序序列)的根节点的位置
{
if(str2[i]==str1[n-1])
break;
}
printf("%c",root->data);
root->left=creattree(i,str1,str2);//(左子树的长度,左子树在str1中开始位置的地址,左子树在str2中开始位置的地址)
root->right=creattree(n-i-1,str1+i,str2+i+1);//(右子树的长度,右子树在str1中开始位置的地址,右子树在str2中开始位置的地址)
//后序遍历输出
return root;
};
int main()
{
int n,t,j;
char str1[1100],str2[1100];
scanf("%d",&t);
for(j=0;j<=t-1;j++)
{
scanf("%s",str1);
scanf("%s",str2);
n=strlen(str2);
creattree(n,str2,str1);
printf("\n");
}
return 0;
}
1222

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



