Reconstruct the binary tree topic description
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.
Implementation code
functionReconstructbinarytree (Pre, VIN) {if(!pre | | pre.length===0){ return; } varroot={val:pre[0] }; for(vari=0;i<pre.length;i++){ if(vin[i]==pre[0]) {root.left= Reconstructbinarytree (Pre.slice (1,i+1), Vin.slice (0, i)); Root.right= Reconstructbinarytree (Pre.slice (i+1), Vin.slice (i+1)); } } returnRoot;}Related knowledge
A two-fork tree is a tree structure with up to two subtrees per node.
The pre-sequence traversal: First accesses the root, then the first sequence traverses the left subtree, and finally the first sequence traverses the right sub-tree.
Middle Sequence traversal: first the middle sequence traverses the left subtree, then accesses the root, and finally the middle sequence traverses the right subtree.
Post-post traversal: The first step to traverse the left sub-tree, and then to traverse the right subtree, the last access to the root.
Ideas
The first position of the ordinal traversal is the root node TreeNode, locating the root node position of the middle sequence traversal in the center I;
Then the left side of the middle sequence traversal I is the ordinal group of left words, and the right is the middle ordinal group of the right subtree.
The second of the first sequence traversal
-javascript (4) reconstruction of the binary tree