Rebuilding a binary tree
Description
The question is very simple. I will give you a post-order and mid-order sequence of a binary tree and find its pre-order sequence (so easy !).
-
Input
-
The input contains multiple groups of data (less than 100 groups), ending with a file. Each group contains only one row of data, including two strings separated by spaces, indicating the post-order and Middle-order sequences of Binary Trees (the string length is less than 26, and the input data is valid ).
-
Output
-
Each group of output data occupies a single row. The output data must be sorted first.
-
Sample Input
-
ACBFGED ABCDEFGCDAB CBAD
-
Sample output
-
DBACEGFBCAD
#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;}
Rebuilding a binary tree