求二叉树的先序遍历

求二叉树的先序遍历

Description

 已知一棵二叉树的中序遍历和后序遍历,求二叉树的先序遍历

Input

 输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的中序遍历序列,第二个字符串表示二叉树的后序遍历序列。 

Output

 输出二叉树的先序遍历序列

Sample

Input 

2
dbgeafc
dgebfca
lnixu
linux

Output 

abdegcf
xnliu

Hint

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 struct node
 5 {
 6     char num;
 7     struct node *l,*r;
 8 };
 9 struct node *f(char j[],int n,char i[])
10 {
11     if(n<=0)
12         return NULL;
13     struct node *root;
14     root=(struct node *)malloc(sizeof(struct node));
15     root->num=j[n-1];
16     int v;
17     for(v=0;v<n;v++)
18         if(i[v]==j[n-1])break;
19     root->l=f(j,v,i);
20     root->r=f(j+v,n-v-1,i+v+1);
21     return root;
22 };
23 
24 void f1(struct node *head)
25 {
26     if(head==NULL)
27         return ;
28     printf("%c",head->num);
29     f1(head->l);
30     f1(head->r);
31 }
32 int main()
33 {
34     int a,b;
35     char i[1000],j[1000];
36     struct node *head;
37     scanf("%d",&b);
38     while(b--)
39     {
40         scanf("%s %s",i,j);
41         a=strlen(i);
42         head=f(j,a,i);
43         f1(head);
44         printf("
");
45     }
46     return 0;
47 }
原文地址:https://www.cnblogs.com/xiaolitongxueyaoshangjin/p/12722088.html