The topic describes the input of a binary tree's pre-sequence traversal and the results of the middle sequence traversal, please reconstruct the two-fork tree. Assume that no duplicate numbers are included in the result of the input's pre-order traversal and the middle-order traversal. For example, enter the 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}, then rebuild the binary tree and return.
1 /**2 * Definition for binary tree3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */ Ten One structtreenode* Reconstructbinarytree (vector<int> pre,vector<int>inch) { A if(pre.size () = =0||inch. Size () = =0) - { - returnNULL; the } - if(pre.size () = =1) - { - return NewTreeNode (Pre.front ()); + } - if(inch. Size () = =1) + { A return NewTreeNode (inch. Front ()); at } - intNode_val=pre.front ();//the value used to stub the node -Auto Node_in=find (inch. Begin (),inch. End (), node_val);//The location of the root node in - - //Left dial hand tree range -vector<int> Left_in_block (inch. Begin (), node_in); in intmove=node_in-inch. Begin (); -vector<int> Left_pre_block (++pre.begin (), Pre.begin () +move+1); to + //Right sub-tree interval -vector<int> Right_in_block (++node_in,inch. End ()); thevector<int> Right_pre_block (pre.begin () +move+1, Pre.end ()); * $TreeNode *node=NewTreeNode (Node_val);//root nodePanax Notoginsengnode->left=Reconstructbinarytree (left_pre_block,left_in_block); -node->right=Reconstructbinarytree (right_pre_block,right_in_block); the returnnode; +}
Reconstruction of binary tree based on binary tree's pre-sequence traversal and middle sequence traversal