Algorithm for post-order traversal based on binary tree pre-sequence traversal and middle sequence traversal sequence

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.