题目描述很简单
Time Limit : 3000/1000ms (Java/Other) Memory Limit : 65535/32768K (Java/Other)
Total Submission(s) : 12 Accepted Submission(s) : 2
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
输入一棵树的中序遍历和先序遍历,输出后序遍历。
Input
输入多组数据。
每组数据的第一行: 树的中序遍历。
每组数据的第二行: 同样的树的前序遍历。
每组数据的第一行: 树的中序遍历。
每组数据的第二行: 同样的树的前序遍历。
Output
每组数据输出这棵树树的后序遍历。
Sample Input
ABEDFCHG CBADEFGH
Sample Output
AEFDBHGC
Author
思路:分冶法创建二叉树,多少遍了还是没做出来,再写一遍警示自己!!!
#include <iostream>
#include <string>
using namespace std;
int mid[10000],before[10000];
int lt[10000],rt[10000];
int build(int L1,int R1,int L2,int R2){
if(L1 > R1) return 0;
int root = before[L2];
int p = L1;
while(mid[p] != root) p++;
int cnt = p-L1;
lt[root] = build(L1,p-1,L2+1,L2+cnt);
rt[root] = build(p+1,R1,L2+cnt+1,R2);
return root;
}
void Out_put(int p){
if(!p) return ;
Out_put(lt[p]);
Out_put(rt[p]);
cout<<(char)p;
}
int main()
{
string in,out;
while(cin>>in>>out){
int len = in.size();
for(int i = 0;i < len;i ++) mid[i] = (int)in[i];
for(int i = 0;i < len;i ++) before[i] = (int)out[i];
build(0,len-1,0,len-1);
/* for(int i = 0;i < len;i ++)
cout<<(char)mid[i]<<" lt: "<<(char)lt[mid[i]]<<" rt: "<<(char)rt[mid[i]]<<endl;*/
Out_put(before[0]);
cout<<endl;
}
return 0;
}