求二叉树的先序遍历
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>
typedef struct node{
char data;
node *lchild, *rchild ;
}*tree;
struct node *gettree(tree &t,char *ino, char *pos,int n)
{
if(n <= 0) return NULL ;
t = new node ;
t->data = pos[n-1] ;
int k = strchr(ino,pos[n-1])-ino;
t->lchild = gettree(t->lchild,ino,pos,k);
t->rchild = gettree(t->rchild,ino+k+1,pos+k,n-k-1);
return t ;
}
void getpre(tree t)
{
if(t)
{
printf("%c", t->data);
getpre(t->lchild);
getpre(t->rchild);
}
}
int main()
{
int i , n ;
char ino[100] , pos[100] ;
tree head;
scanf("%d", &n);
for(i = 0 ; i < n ; i++)
{
scanf("%s%s", ino,pos);
gettree(head,ino,pos,strlen(ino));
getpre(head);
printf("\n");
}
}