Leetcode 106.Construct binary tree from Inorder and Postorder traversal (based on the middle sequence traversal and post-order traversal constructs two fork trees)

Source: Internet
Author: User

Given Inorder and Postorder traversal of a tree, construct the binary tree.

Note:
Assume that duplicates does not exist in the tree.

Idea: This problem is similar to the previous one, the first is the root node, and the last is the root node of the post-order traversal. The rest of the steps are similar.

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[] inorder, int[] postorder) {/** * 1. According to the post-post traversal, first         Determine the 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. Recursively solves the left and right subtree of the root node */        if (Postorder.length = = 0 | | inorder.length = = 0) return null;        TreeNode root = new TreeNode (postorder[postorder.length-1]);        int k = 0;            for (; k < inorder.length; k++) {if (inorder[k] = = Postorder[postorder.length-1]) {break;        }} int[] P1 = Arrays.copyofrange (postorder,0,k);        int[] q1 = arrays.copyofrange (postorder,k,postorder.length-1);        int[] P2 = arrays.copyofrange (inorder,0,k);                int[] q2 = Arrays.copyofrange (inorder,k+1,inorder.length);   Root.left = Buildtree (P2,P1);     Root.right = Buildtree (Q2,Q1);    return root; }}



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

Leetcode 106.Construct binary tree from Inorder and Postorder traversal (based on the middle sequence traversal and post-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.