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

时间:2023-03-08 15:44:24
【递归】Vijos P1132 求二叉树的先序序列(NOIP2001普及组第三题)

题目链接:

  https://vijos.org/p/1132

题目大意

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

题目思路:

  【递归】

  这题妥妥递归。

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

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

 //
//by coolxxx
//
#include<iostream>
#include<algorithm>
#include<string>
#include<iomanip>
#include<memory.h>
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
#include<math.h>
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
#define abs(a) ((a)>0?(a):(-(a)))
#define lowbit(a) (a&(-a))
#define sqr(a) ((a)*(a))
#define swap(a,b) ((a)^=(b),(b)^=(a),(a)^=(b))
#define eps 1e-8
#define J 10000
#define MAX 0x7f7f7f7f
#define PI 3.1415926535897
#define N 1504
using namespace std;
int n,m,lll,ans,cas;
char s1[N],s2[N];
void work(int l1,int r1,int l2,int r2)
{
if(l1>r1 || l2>r2)return;
int i;
for(i=l1;i<=r1;i++)if(s1[i]==s2[r2])break;
printf("%c",s2[r2]);
work(l1,i-,l2,l2+i-l1-);
work(i+,r1,l2+i-l1,r2-);
}
int main()
{
#ifndef ONLINE_JUDGE
// freopen("1.txt","r",stdin);
// freopen("2.txt","w",stdout);
#endif
int i,j,k;
while(~scanf("%s",s1))
// while(~scanf("%d",&n) && n)
{
scanf("%s",s2);
n=strlen(s1);
work(,n-,,n-);
puts("");
}
return ;
} /*
// //
*/