題目描述
輸入二叉樹的前序遍歷和中序遍歷結果,輸出二叉樹的後序遍歷結果
輸入格式
第一行爲二叉樹先序遍歷結果
第二行爲二叉樹中序遍歷結果。
輸出格式
二叉樹後序遍歷結果。
Example
Inputs
426315
623415
Outputs
632514
實現代碼:
#include<bits/stdc++.h>
using namespace std;
char a[1003],b[1003];
struct Node
{
//char a;
int l,r;
}no[1003];
int rebuild(int l1,int r1,int l2,int r2)
{
int i,j;
char c=a[l1];
int t=c-'0';
if(l1==r1)return t;//遞歸終止
for(i=l2;i<=r2;++i)
{
if(b[i]==c)break;
}
int len=i-l2;
//cout<<len<<endl;
if(len>0)no[t].l=rebuild(l1+1,l1+len,l2,l2+len-1);
//if判斷不要遺漏了,確保左下標<=右下標
if(len<r1-l1)no[t].r=rebuild(l1+len+1,r1,l2+len+1,r2);
return t;
}
void post(int t)
{
if(no[t].l!=-1)post(no[t].l);//if判斷不要遺漏了
if(no[t].r!=-1)post(no[t].r);
printf("%d",t);
}
int main()
{
memset(no,-1,sizeof(no));
while(~scanf("%s %s",a,b))
{
//cout<<strlen(b)-1<<endl;
rebuild(0,strlen(a)-1,0,strlen(b)-1);
post(a[0]-'0');
printf("\n");
}
return 0;
}