codevs 2010 求后序遍历x

题目描述 Description

输入一棵二叉树的先序和中序遍历序列,输出其后序遍历序列。

输入描述 Input Description

共两行,第一行一个字符串,表示树的先序遍历,第二行一个字符串,表示树的中序遍历。

输出描述 Output Description

仅一行,表示树的后序遍历序列。

样例输入 Sample Input

abdehicfg

dbheiafcg

样例输出 Sample Output

dhiebfgca

数据范围及提示 Data Size & Hint

输入长度不大于255。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream> 
 4 
 5 using namespace std;
 6 
 7 /*
 8 s1=abdehicfg
 9 s2=dbheiafcg
10 */
11 
12 string s1,s2;//定义输入的字符串 
13 
14 void calc(int l1,int r1,int l2,int r2)
15 {
16      int m=s2.find(s1[l1]);
17 /*
18 从s2中寻找s1的第一个字符,样例中为a,返回5,m=5
19 此时l2为0
20 故m>l2,将l1=l1(0)+m(5)-l2(0)+1=6,r1不变,l2=m+1=5+1=6,r2不变; 
21 所以变成6,8,6,8
22 ……………… 
23 最后输出 
24 */
25      if(m>l2) calc(l1+1,l1+m-l2,l2,m-1);
26      if(m<r2) calc(l1+m-l2+1,r1,m+1,r2);
27      cout<<s1[l1];
28 }
29 
30 int main()
31 {
32     cin>>s1>>s2;
33     calc(0,s1.length()-1,0,s2.length()-1);//从寻找s1中第0个字符开始
34     //r1初始状态为s1的长度减去1,(因为数组是从0开始计数)r2初始状态为s2的长度减去1 
35     cout<<endl;
36     return 0;
37 }

如果运气好也是错,那我倒愿意错上加错!

❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀

原文地址:https://www.cnblogs.com/zxqxwnngztxx/p/6648360.html