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.According to their characteristics, the first element of the pre-order is the root node, and the middle sequence corresponds to the Saozi of the right subtree of the two-tree. then recursive loops, looking for the same element, this is the root node of the subtree, and then continues the operation until the subtree is empty. Arrays.copyofrange (byte[] original, int from, int to) is a copy of the specified position of the array. Here's the code for the implementation:
1 /**2 * Definition for binary tree3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode (int x) {val = x;}8 * }9 */Ten ImportJava.util.*; One A Public classSolution { - PublicTreeNode Reconstructbinarytree (int[] Pre,int[] in) { - if(Pre = =NULL|| in = =NULL|| Pre.length = = 0 | | In.length = = 0) { the return NULL; - } -TreeNode root =construct (pre, in); - returnRoot; + } - + PrivateTreeNode Construct (int[] Pre,int[] in) { A intLength =pre.length; at if(length = = 0) - return NULL; -TreeNode root =NewTreeNode (pre[0]); - inti = 0; - for(; i < length; i++) { - if(In[i] = = Pre[0]) in Break; - } to if(i = =length) +i--; - int[] Leftpre = Arrays.copyofrange (pre, 1, i + 1); the int[] Rightpre = Arrays.copyofrange (pre, i + 1, length); * int[] LeftIn = Arrays.copyofrange (in, 0, i); $ int[] RightIn = Arrays.copyofrange (in, i + 1, length);Panax NotoginsengRoot.left =construct (Leftpre, leftin); -Root.right =construct (Rightpre, rightin); the returnRoot; + } A}
Rebuilding a binary tree