6-3 二叉树的重建 uva536

时间:2023-03-08 17:09:50

已知先序和中序  求后序

可以有两种方式输出

一种是建好树按照树输出

一种是不建树  在遍历的过程中存入vector  再倒叙输出

#include<bits/stdc++.h>
using namespace std; int ri[];int le[];
char xian[],zhong[];vector<char>ans; int built(int x1,int y1,int x2,int y2)
{
if(x2>y2||x1>y1)return ; char root=xian[x1];
ans.push_back(root);
int p=x2;
while(zhong[p]!=root)p++;
int cnt=p-x2; ri[root]=built(x1+cnt+,y1,x2+cnt+,y2);
le[root]=built(x1+,x1+cnt,x2,x2+cnt-);
return root; } void dfs(int root)
{ if(le[root]){dfs(le[root]);}
if(ri[root]){dfs(ri[root]);}
printf("%c",root);
return;
} int main()
{ while(scanf("%s %s",xian+,zhong+)==)
{ ans.clear(); int n=strlen(xian+); int root=built(,n,,n); //for(int i=ans.size()-1;i>=0;i--)
// cout<<ans[i];
dfs(root);
cout<<endl; } return ;
}