标签:style blog io color ar os for sp strong
描述
题目很简单,给你一棵二叉树的后序和中序序列,求出它的前序序列(So easy!)。
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; }
标签:style blog io color ar os for sp strong
原文地址:http://www.cnblogs.com/imwtr/p/4069618.html