Problem model: It is known that a binary tree pre-sequence traversal sequence is 1,2,3,4,5,6, the middle sequence traversal is 3,2,4,1,6,5, and the design program calculates the order sequence.
In this case, you can create a tree through the pre-sequence traversal and the middle sequence traversal, and then solve it through the post-order traversal, and of course, directly infer the order sequence directly according to the known two sequences, this article will introduce this kind of analysis.
Using recursive thinking, the former sequence can determine the root node is the first element, according to the sequence can determine the left and right sub-tree node set, and then for the left and right sub-tree to continue to determine, the specific algorithm expressed as follows:
void Solve (int preL, int inL, int postl, int n)
{if (n==0) return;
if (n==1) {Post[postl] = Pre[prel]; return;}
root = Pre[prel];
Post[postl+n-1] = root;
for (i=0; i<n; i++)
if (in[inl+i] = = root) break;
L = i; R = n-l-1;
Solve (prel+1, InL, Postl, L);
Solve (prel+l+1, inl+l+1, Postl+l, R);
}
Where Prel,inl,postl is the first coordinate of 3 series, and the array pre,in,post represents the sequence, each time the function can determine the position of the root node of a local subtree in the post order sequence, the key position of the recursive left and right subtree lies in the first position of the pre-order, the end condition of recursion (when n= 0 o'clock, it is indicated that the number of nodes of the subtree is 0, there is no post order sequence, so it is returned directly; when N=1, it is indicated that the number of subtree nodes is 1, the sequence is the node itself, directly assign value can be the key to the success of the program.