重建二叉树
描述
题目很简单,给你一棵二叉树的后序和中序序列,求出它的前序序列(So easy!)。
- 输入
- 输入有多组数据(少于100组),以文件结尾结束。 每组数据仅一行,包括两个字符串,中间用空格隔开,分别表示二叉树的后序和中序序列(字符串长度小于26,输入数据保证合法)。
- 输出
- 每组输出数据单独占一行,输出对应得先序序列。
- 样例输入
-
ACBFGED ABCDEFG CDAB CBAD
- 样例输出
-
DBACEGF BCAD
#include <iostream> #include <string.h> using namespace std; struct tree { char data; tree *left; tree *right; }; tree *converse(char *pos,char *in,int n,int m) { tree *b; int k=0; char *p,*q,*maxp; int maxpost,maxin; if(n<=0) { return NULL; } maxpost=-1; for(p=in;p<in+n;p++) for(q=pos;q<pos+m;q++) if(*p==*q) { k=q-pos; if(k>maxpost) { maxpost=k; maxp=p; maxin=p-in; } } b=new tree; b->data=pos[maxpost]; b->left=converse(pos,in,maxin,m); b->right=converse(pos,maxp+1,n-maxin-1,m); return b; } void pre(tree *b) { if(b) { cout<<b->data; pre(b->left); pre(b->right); } } int main() { char c1[1000],c2[1000]; while(cin>>c1>>c2) { tree *b; b=converse(c1,c2,strlen(c1),strlen(c2)); pre(b); cout<<endl; } return 0; }