Leetcode 105.Construct binary tree from preorder and inorder traversal (based on pre-sequence traversal and middle-order traversal constructs two-fork trees)

Source: Internet
Author: User

Given Preorder and inorder traversal of a tree, construct the binary tree.

Note:

Assume that duplicates does not exist in the tree.

Idea: First, according to the pre-order traversal to get the root node, and then in the middle sequence traversal to get the root node position, the left is the left dial hand tree, the right is the right sub-tree.

Then, the structure of the right subtree of Saozi can be solved recursively. The code is as follows:

/** * Definition for a binary tree node.  * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public TreeNode buildtree (int[] preorder, int[] inorder) {/** * 1. Based on the pre-order traversal, first determine Root node * 2. Then find the root node in the middle sequence traversal, and determine the location of the root node in the middle order traversal * 3. Segmentation of the left and right subtree based on the index location * 4. Recursive solution to the left and right subtree of the root node */I        F (preorder.length = = 0 | | inorder.length = = 0) return null;        TreeNode root = new TreeNode (preorder[0]);        int k = 0;            for (; k < inorder.length; k++) {if (inorder[k] = = Preorder[0]) {break;        }} int[] P1 = Arrays.copyofrange (preorder,1,k+1);        int[] q1 = arrays.copyofrange (preorder,k+1,preorder.length);        int[] P2 = arrays.copyofrange (inorder,0,k);                int[] q2 = Arrays.copyofrange (inorder,k+1,inorder.length);        Root.left = Buildtree (P1,P2);     Root.right = Buildtree (Q1,Q2);   return root; }}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode 105.Construct binary tree from preorder and inorder traversal (based on pre-sequence traversal and middle-order traversal constructs two-fork trees)

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.