Binary tree: Determining tree structure based on two traversal sequences (Build-tree)

Source: Internet
Author: User
Topic description
Input
Line 1th: two fork Tree sequence traversal order 2nd: Middle Sequence Traversal order


Output
Sequential traversal sequence of binary tree


Sample input
Copy (if you copy to the console without wrapping, you can paste to a text editor and then copy)


Abcdefgh
Cbedaghf
Sample output

Cedbhgfa


-------------------------------------------------------------------------------------


It is estimated that a lot of people begin to think that the structure of a tree can be obtained by using first-order traversal information. However, there will be many different kinds of trees if you only use first-order traversal information.

So, that's not going to work.

In fact, if you think about it, you can find that we can get the root node of the whole tree by first order, and then find it in the middle order. Thus, the whole sequence is divided into two parts, namely the Saozi right subtree of the original tree.

At this point, we can solve the problem by recursion.


-----------------------------------------------------------------------------------------


















See here, estimate everybody's first idea is the achievement. In fact, there is no need for achievement. After acquiring the root node of the (subtree) tree, it is possible to print the sequence of the Saozi right subtree recursively, preferably by printing the root node.

This saves the time to build and the memory of storing the tree.

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.