求二叉树的先序遍历
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描写叙述
已知一棵二叉树的中序遍历和后序遍历,求二叉树的先序遍历
输入
输入数据有多组,第一行是一个整数t (t<1000),代表有t组測试数据。每组包含两个长度小于50 的字符串,第一个字符串表示二叉树的中序遍历序列,第二个字符串表示二叉树的后序遍历序列。
输出
输出二叉树的先序遍历序列
演示样例输入
2 dbgeafc dgebfca lnixu linux
演示样例输出
abdegcf xnliu
提示
来源
GYX
演示样例程序
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
char data;
struct node *left,*right;
};
struct node *root;
struct node *creat(int n,char *str1,char *str2)
{
int i;
if(n==0)
return NULL;
root=(struct node *)malloc(sizeof(struct node));
root->data=str2[n-1];//找到根节点
for(i=0;i<n;i++)//找到str1中的根节点的位置
{
if(str1[i]==str2[n-1])
break;
}
printf("%c",root->data);//输出头结点
root->left=creat(i,str1,str2);//(左子树的长度,str1中左子树開始位置的地址,str2中左子树開始位置的地址)
root->right=creat(n-i-1,str1+i+1,str2+i);//(右子树的长度,str1中右子树開始位置的地址,str2中右子树開始位置的地址)
return root;
};
int main()
{
int n;
char str1[110],str2[110];
scanf("%d",&n);
while(n--)
{
scanf("%s",str1);
scanf("%s",str2);
int len=strlen(str1);
creat(len,str1,str2);
printf("\n");
}
return 0;
}