/* Enter the result of the pre-order traversal and the middle sequence traversal of a binary tree, and rebuild 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. /** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: structtreenode* Constructbinarytree (vector<int> Pre,intPrestart,intpreend,vector<int>inch,intInstart,intinend) {TreeNode* Root =NewTreeNode (Pre[prestart]); if(Preend = = Prestart) && (inend = = Instart) && (inch[instart]==Pre[prestart])) returnRoot; inti =Instart; while((i<=inend) && (inch[i]!=Pre[prestart])) {i++; } intLenf = i-Instart; intLENR = Inend-i; intLeftpreend = prestart+Lenf; if(lenf>0) {root->left = Constructbinarytree (pre,prestart+1, Leftpreend,inch, instart,i-1); } if(lenr>0) {root->right = Constructbinarytree (pre,leftpreend+1, Preend,inch, i+1, Inend); } returnRoot; } structtreenode* Reconstructbinarytree (vector<int> pre,vector<int>inch) { intLen =pre.size (); if(len = =0)returnNULL; returnConstructbinarytree (PRE,0, len-1,inch,0, len-1); }};
Rebuilding a binary tree