POJ 2255 Tree Recovery
思路:递归左子树、右子树
#include<iostream> #include<assert.h> using namespace std; char preord[30],inord[30]; void recover(int preleft,int preright,int inleft,int inright) { int root,leftsize,rightsize; assert(preleft<=preright && inleft<=inright);//条件不满足时,结束函数 for(root=inleft;root<=inright;root++) if(preord[preleft]==inord[root]) break; leftsize =root-inleft; rightsize=inright-root; if(leftsize>0) recover(preleft+1,preleft+leftsize,inleft,root-1); if(rightsize>0) recover(preleft+leftsize+1,preright,root+1,inright); cout<<inord[root]; } void solve_case() { int n=strlen(preord); recover(0,n-1,0,n-1); cout<<endl; } int main() { while(cin>>preord>>inord) solve_case(); return 0; }