|
A classic problem in binary trees is that given the pre-order traversal sequence and middle-order traversal sequence of a given binary tree, find the subsequent traversal sequence. It is easier to solve with the idea of recursion. code show as below:
/*
a is the preorder sequence
b is the in-order sequence
The subsequent sequence will be saved in c
*/
void PostOrder(const char a[], const char b[], char c[], int starta, int startb, int startc, int len)
{
if(len==0) return;
if(len==1) {c[startc] = a[starta]; return;}
c[startc+len-1] = a[starta];//Handle tree root
int i = startb;
while(b[i]!=a[starta]) ++i;
int leftlen = i-startb;
int rightlen = len-leftlen-1;
PostOrder(a,b,c,starta+1,startb,startc,leftlen);//Construct the PostOrder of the left subtree
PostOrder(a,b,c,starta+leftlen+1,startb+leftlen+1,startc+leftlen,rightlen);//Construct the PostOrder of the right subtree
}
void PostOrder(const char a[], const char b[], char c[])
{
int len = strlen(a);
PostOrder(a,b,c,0,0,0,len);
c[len] = '\0';
}
Among them is the process of construction,
You can study it. . . . . . . |
|