To enter the results of the pre-order traversal and the middle sequence traversal of a binary tree, 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.
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 classSolution { One Public: A structtreenode* Reconstructbinarytree (vector<int> pre,vector<int>inch) { -treenode* t=NewTreeNode (pre[0]); - if(pre.size () = =1&&inch. Size () = =1) the returnT; - intCount=0; - while(pre[0]!=inch[Count]) { -count++; + } -vector<int> pre_l (pre.begin () +1, Pre.begin () +count+1); +vector<int> Pre_r (pre.begin () +count+1, Pre.end ()); Avector<int> in_l (inch. Begin (),inch. Begin () +count); atvector<int> In_r (inch. Begin () +count+1,inch. End ()); - if(!pre_l.empty ()) -t->left=Reconstructbinarytree (pre_l,in_l); - if(!pre_r.empty ()) -t->right=Reconstructbinarytree (pre_r,in_r); - returnT; in - } to};
The first number of pre-sequence traversal is the root node, and the left dial hand tree before the middle sequence traverses the root node is the right subtree. After that, the left and right subtrees are treated in the same way.
Rebuilding a binary tree