To reconstruct the binary tree, we know the order and sequence of the output binary tree.
#include <iostream>#include<cstdio>#include<cstring>using namespacestd;Const intM =1005;inti,j,k;intMax (intXinty) {returnX>y?x:y;}voidBuildintNChar*S1,Char*S2) { if(n<=0)return ; intp = STRCHR (s2,s1[0])-S2;//find the location of the root node in the middle sequence traversalBuild (p,s1+1, S2); Build (n-p-1, s1+p+1, s2+p+1); printf ("%c", s1[0]);}intMain () {Chars1[ -],s2[ -]; scanf ("%s%s", S1,S2); intLen =strlen (S1); Build (LEN,S1,S2);return 0;}View Code
The following is a nyoj on the data structure of the problem, know the sequence and order to order first. Before looking at what the pointer is really drunk, but yesterday review the data structure, or it with the structure and pointers to achieve
#include <iostream>#include<cstdio>#include<cstring>#include<cstdlib>using namespacestd;Const intM =1005; typedefstructbtnode{Chardata; Btnode*lchild,*rchild;}; Btnode*creat (Char*post,Char*inch,intN) {Btnode*R; Charr,*p; intK; if(n<=0)returnNULL; R= * (post + N-1); S= (Btnode *) malloc (sizeof(Btnode)); S->data =R; for(p=inch;p <inch+n;p++){ if(*p = = r) Break; } k= P-inch; S->lchild = Creat (post,inch, K); S->rchild = creat (post+k,p+1, n-k-1); returns;}voidPre (Btnode *s) { if(s!=NULL) {printf ("%c",s->data); Pre (S-lchild); Pre (S-rchild); }}intMain () {Chars1[ -],s2[ -]; Btnode*p; while(SCANF ("%s%s", s1,s2)! =EOF) { intLen =strlen (S1); P=creat (S1,s2,len); Pre (P); printf ("\ n"); }return 0;}
Data structure Reconstruction binary tree