1169 二叉树遍历(XCOJ DFS)

给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度≤8)。

样例输入

BADC
BDCA

样例输出

ABCD
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 char ch1[15],ch2[15];
 7 int len1,len2;
 8 int dfs(int s,int e,int a,int b)
 9 {
10     int i,j;
11     if(s>e)
12         return 0;
13     printf("%c",ch2[e]);
14     if(s==e)
15         return 0;
16     for(i=a;i<=b;i++)
17         if(ch1[i]==ch2[e])
18             break;
19     int l=i-a,r=b-i;
20     dfs(s,s+l-1,a,i-1);
21     dfs(s+l,e-1,i+1,b);
22     return 0;
23 }
24 int main()
25 {
26     freopen("in.txt","r",stdin);
27     while(scanf("%s%s",ch1,ch2)!=EOF)
28     {
29         len1=strlen(ch1),len2=strlen(ch2);
30         dfs(0,len2-1,0,len1-1);
31         printf("\n");
32     }
33 }

 

posted @ 2016-03-16 19:56  御心飞行  阅读(198)  评论(0编辑  收藏  举报