【递归】Vijos P1132 求二叉树的先序序列(NOIP2001普及组第三题)

题目链接:

  https://vijos.org/p/1132

题目大意

  给定二叉树的中序和后序遍历,求该二叉树先序遍历。

题目思路:

  【递归】

  这题妥妥递归。

  二叉树先序根左右,中序左根右,后序左右根。

  对于每一颗子树,它的后序最后一个必定是根,于是可以根据根在中序的位置把左子树和右子树区分开来。

 

 1 //
 2 //by coolxxx
 3 //
 4 #include<iostream>
 5 #include<algorithm>
 6 #include<string>
 7 #include<iomanip>
 8 #include<memory.h>
 9 #include<time.h>
10 #include<stdio.h>
11 #include<stdlib.h>
12 #include<string.h>
13 #include<stdbool.h>
14 #include<math.h>
15 #define min(a,b) ((a)<(b)?(a):(b))
16 #define max(a,b) ((a)>(b)?(a):(b))
17 #define abs(a) ((a)>0?(a):(-(a)))
18 #define lowbit(a) (a&(-a))
19 #define sqr(a) ((a)*(a))
20 #define swap(a,b) ((a)^=(b),(b)^=(a),(a)^=(b))
21 #define eps 1e-8
22 #define J 10000
23 #define MAX 0x7f7f7f7f
24 #define PI 3.1415926535897
25 #define N 1504
26 using namespace std;
27 int n,m,lll,ans,cas;
28 char s1[N],s2[N];
29 void work(int l1,int r1,int l2,int r2)
30 {
31     if(l1>r1 || l2>r2)return;
32     int i;
33     for(i=l1;i<=r1;i++)if(s1[i]==s2[r2])break;
34     printf("%c",s2[r2]);
35     work(l1,i-1,l2,l2+i-l1-1);
36     work(i+1,r1,l2+i-l1,r2-1);
37 }
38 int main()
39 {
40     #ifndef ONLINE_JUDGE
41 //    freopen("1.txt","r",stdin);
42 //    freopen("2.txt","w",stdout);
43     #endif
44     int i,j,k;
45     while(~scanf("%s",s1))
46 //    while(~scanf("%d",&n) && n)
47     {
48         scanf("%s",s2);
49         n=strlen(s1);
50         work(0,n-1,0,n-1);
51         puts("");
52     }
53     return 0;
54 }
55 
56 
57 /*
58 //
59 
60 //
61 */
View Code

 

posted @ 2016-04-09 00:15  Cool639zhu  阅读(241)  评论(0编辑  收藏  举报