The binary tree generates a binary tree based on the pre-order array and the mid-order traversal array.
Question: a binary tree is generated by means of forward and middle traversal of a given binary tree.
Example:
PreArr []: {1, 2, 4, 5, 3, 6, 7}
In-order traversal array: inArr []: {, 7}
The generated binary tree is as follows:
Solution:
We can see from the nature of the forward variable of the binary tree that preArr [0] is the root node of the array. We can see from the nature of the central traversal of the binary tree that {, 5} is the left subtree of the binary tree, {6, 3, 7} on the right subtree, repeat this operation to construct a binary tree.
Public class Solution {public TreeNode reConstructBinaryTree (int [] pre, int [] in) {TreeNode root = new TreeNode (pre [0]); // The first number in the preorder is set to root int len = pre. length; // if (len = 1) {root. left = null; root. right = null; return root;} // locate the root position int rootval = root in the middle order. val; int I; for (I = 0; I <len; I ++) {if (rootval = in [I]) break ;} // create the left subtree if (I> 0) {int [] pr = new int [I]; int [] ino = new int [I]; for (int j = 0; j <I; j ++) {pr [j] = pre [j + 1];} for (int j = 0; j <I; j ++) {ino [j] = in [j];} root. left = reConstructBinaryTree (pr, ino);} else {root. left = null;} // create the right subtree if (len-I-1> 0) {int [] pr = new int [len-I-1]; int [] ino = new int [len-I-1]; for (int j = I + 1; j <len; j ++) {ino [j-I-1] = in [j]; pr [j-I-1] = pre [j];} root. right = reConstructBinaryTree (pr, ino);} else {root. right = null;} return root;} public static void main (String [] args) {int [] preArr = {1, 2, 4, 5, 3, 6, 7}; int [] inArr = {4, 2, 5, 1, 6, 3, 7}; Solution s = new Solution (); TreeNode root = s. reConstructBinaryTree (preArr, inArr); s. postOrder (root );}