Restore the binary tree--6 with the result of a binary tree's pre-sequence traversal and the sequence traversal results

Source: Internet
Author: User

The binary tree is reconstructed by inputting the sequence traversal of a binary tree and the result of the middle sequence traversal, assuming that there are no duplicate numbers in the result of the input's pre-order traversal and the middle sequence traversal. For example, the input pre-sequence traversal sequence {1,2,4,7,3,5,6,8} and the middle sequence traversal sequence {4,7,2,1,5,3,8,6}, rebuilds the two-bit tree that satisfies the pre-order traversal and the middle-order traversal and outputs its head node.

The order of the pre-order traversal of a binary tree is "the left node, the root node, and the right node", and the order of the sequence traversal is the "left knot----------The right knot", so the general idea is Jiangzi:

    1. In the pre-sequence traversal list, the first data is definitely the root node, and the first data in the sequence traversal list is definitely the leftmost node of the tree , so we can know that in the pre-sequence traversal, from the root node to the leftmost node must be the left branch of the tree, that is, "1->2->4";

    2. Next, in the middle sequence traversal, after accessing the leftmost node 4, because its left node is null to access the left side of the right branch of 4 is the leftmost node, 7, and in the pre-sequence traversal access to the leftmost node after access to the right node, found also 7, indicating that 7 is the left node 4 of the right branch on the left node, That is, there are only 71 right nodes;

    3. Then, after accessing the leftmost node in the middle sequence traversal, that is, 4 is the root node of the subtree, it is necessary to go back to the 4 nodes of the parent, that is, 2, and then down access is the root node 1, that is, 2 and no right node;

    4. At this point, 1 is the root node of the left subtree has been all access finished;


There is no further analysis, because it will be found that the above said a bunch of trees can be rebuilt, but it is cumbersome, logically related but difficult to dredge up a coherent, so want to convert to code to achieve presumably is a great expense;

Why the analysis to the 4th stop, is because the 4th type of conversion of the new idea of a starting point:

    1. First of all, in front of the 1th bold font must be no problem, the first data in the pre-sequence traversal must be the root node of the tree ;

    2. Combined with the 4th, this root node is found in the middle sequence traversal. It will be found that the data in front of the root node in 1 is the left subtree of 1, there are three nodes, then in the preceding sequence traversal 1 of the three nodes are all belong to the left subtree, so the data after 1 must also be on the right subtree of 1, there are four nodes;

    3. Next look at the previous sequence traversal followed by 1 after the data 2 is on the left or right side of 1, on the left is 1 of the left node, on the right side is 1 of the right node;

    4. And then according to the order of the sequence traversal list of 2 as a new root node, then the data on its left is its left subtree, the right side of the data is on the right subtree, of course, until the end of the previous root node 1; and then cycle from the previous step;


Can draw as follows:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/7F/81/wKioL1chXFyD1KAtAAAXq_-pAZY295.png "title=" tree graph. png "alt=" Wkiol1chxfyd1kataaaxq_-pazy295.png "/>


Do you find that the second analysis is more straightforward than the first? and logically repetitive, such analysis is easier to implement in code, and can be implemented with recursion:

#include  <iostream> #include  <assert.h>using namespace std;typedef int  data_type;//first defines the structure of a tree node and implements the constructor struct binarytreenode{    data_type _data;     BinaryTreeNode* _Lnode;    BinaryTreeNode* _Rnode;     binarytreenode (data_type data)         :_data ( Data)         ,_lnode (NULL)          ,_rnode (NULL)     {}  };//rebuilds the binary tree with a parameter of two traversal lists, the number of tree nodes, and recursion needs to know the extent of the subtree Binarytreenode* rebuildbinarytree (const data_type* prevlist, const data _type *inlist, const size_t num, size_t head, size_t tail) {     assert (prevlist && inlist && num);   //Judgment parameter validity     //the first node in a pre-sequence traversal list must be the root node of the tree &nbsP;   binarytreenode *root = new binarytreenode (*prevlist);     size_t root_index;    //the root node     for (root_) in the Sequence traversal list. Index = 0; root_index < num; ++root_index)     {            if (Inlist[root_index] == *prevlist)             break;    }        if (inlist[root_index] != *prevlist)   // Checks whether the given sequence is a valid traversal sequence     {            cout<< "Invalid parameter ..." <<endl;        exit (0);     }       //when the number of nodes is greater than 0 indicates that there will be a child node, otherwise the initialized null     //the end of the range is not included in the root node, so pay attention to &nbsThe number of nodes to the left of the p;   size_t left_node_num = root_index - head;//root node      if (left_node_num > 0)         root->_lnode  = rebuildbinarytree (prevlist+1, inlist, num, head, root_index-1);   The number of nodes to the right of the   size_t right_node_num = tail - root_index;//root node      if (right_node_num > 0)         root->_Rnode  = rebuildbinarytree (Prevlist+left_node_num+1, inlist, num, root_index+1, tail);     return root;} The pre-sequence traversal checks whether the two fork tree is correctly rebuilt Void preorder (binarytreenode *root) {    if (root !=  NULL)     {        cout<<root->_data< <         preorder (Root->_lnode);        preorder (Root->_rnode);     }}int main () {     data_type prevorderlist[] = {1, 2, 4, 7, 3, 5,  6, 8};    data_type inorderlist[] = {4, 7, 2, 1,  5, 3, 8, 6};    size_t node_num = sizeof (PrevOrderList )/sizeof (prevorderlist[0]);     //here the first and the end of the representation range are in the middle sequence traversal     size_t  head = 0;    size_t tail = node_num-1;     Binarytreenode* root = rebuildbinarytree (prevorderlist, inorderlist, node_num,  Head, tail);    cout<< "the root data: " <<root->_data <<endl;    preorder (Root);    cout<< "NULL" <<endl;     return 0;} 


To run the program:

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/7F/8A/wKioL1ch6Q3BeRUPAAAPrcxRa-c998.png "title=" Treeret.png "alt=" Wkiol1ch6q3berupaaaprcxra-c998.png "/>


Because it is only checking whether the book is rebuilt, the first sequential traversal of the tree is performed recursively, and the output is found to be the same as a given sequence of sequential traversal, then the tree is reconstructed.


Finish

This article is from the "Knock Code good Sleep zzz" blog, please be sure to keep this source http://2627lounuo.blog.51cto.com/10696599/1768748

Restore the binary tree--6 with the result of a binary tree's pre-sequence traversal and the sequence traversal results

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.