Algorithm: Search for pre-order traversal by post-order traversal and Middle-order traversal

Source: Internet
Author: User

Assume that the post-order traversal sequence of a binary tree is DGJHEBIFCA, the middle-order traversal sequence is DBGEHJACIF, and the pre-order traversal is obtained.

The overall idea is as follows: locate each node through the back-order traversal, then judge the Left and Right Subtrees by the middle-order traversal, restore the entire Binary Tree, and write the forward-order traversal.

The order of post-order traversal is known. The last A is the root node of the binary tree,

Then, divide the Middle-order traversal from A into two sections. The left part of A is the left subtree, And the right part of A is the right subtree,

The result is as follows:


Then look at the subtree on the right,

We can see from the post-order traversal that the post-order traversal of the Left subtree is IFC, and the middle-order traversal is CIF.

Back to the beginning, repeat the previous process. The root node is C in the descending traversal, and the middle traversal is divided into two segments from C,

Left is the left subtree, right is the right subtree

That is, there is only one right subtree on the right,

Repeat the preceding process again. Now, the IF post-order traversal is IF, and the middle-order traversal is IF.

Node F, I is the left subtree of F

In this way, the right subtree of this binary tree is completely restored, and the method of the Left subtree is exactly the same, which is a recursive process. The flowchart is as follows:

NEXT:

The Complete Binary Tree obtained at the end is as follows:

Then write the pre-order traversal, Which is ABDEGHJCFI.

It can be implemented using algorithms and remains here for the moment.

Author: jason0539

Weibo: http://weibo.com/2553717707

Blog: http://blog.csdn.net/jason0539 (reprinted please explain the source)

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.