The binary tree generates a binary tree based on the pre-order array and the mid-order traversal array.

Source: Internet
Author: User

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 );}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.