# [Leetcode] Construct binary tree from inorder and postorder Traversal

Source: Internet
Author: User

Construct binary tree from inorder and postorder Traversal

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

Note:
You may assume that duplicates do not exist in the tree.

Algorithm: very basic. Similar to [leetcode] Construct binary tree from preorder and inorder traversal, a binary tree is constructed based on the central sequence and the post sequence.

` 1 public class Solution { 2     public TreeNode buildTree(int[] inorder, int[] postorder) { 3          if(inorder == null || postorder == null || inorder.length != postorder.length || inorder.length == 0) return null; 4          int length = inorder.length ; 5          int val = postorder[length - 1]; 6          int mid = 0; 7          for(int i = 0; i < length; i++){ 8              if(val == inorder[i]){ 9                  mid = i;10                  break;11              }12          }13          int[] leftInorder = Arrays.copyOfRange(inorder, 0, mid);14          int[] leftPost = Arrays.copyOfRange(postorder, 0, mid);15          int[] rightInorder = Arrays.copyOfRange(inorder, mid + 1, length);16          int[] rightPost = Arrays.copyOfRange(postorder, mid, length - 1);17          TreeNode root = new TreeNode(val);18          root.left = buildTree(leftInorder,leftPost);19          root.right = buildTree(rightInorder, rightPost);20          return root;21      22     }23 }`

Related Keywords:

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.