Construct Binary Tree from inorder and Postorder traversal

Source: Internet
Author: User

The original title is as follows;

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

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

Test instructions is simple: Spanning tree based on sequence traversal and sequential traversal


The idea is simple: according to the sequence of sequential traversal to determine the root node, in the middle sequence traversal to find the root node, the original sequence is divided into the left and right two parts, the recursive resolution of the left and right two parts can solve the problem.

The Java code is as follows:


public class Constructbinarytreefrominorderandpostordertraversal {/** * @Construct Binary Tree from Inorder and Postorder Traversal * link:https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/* Idea: Recursive */class treenode{int val; TreeNode left; TreeNode right;public TreeNode (int x) {val=x;}} Class Solution {public TreeNode buildtree (int[] inorder, int[] postorder) {if (inorder.length==0) {retur        n null;        } TreeNode node=createtree (inorder, 0, inorder.length-1, postorder, 0, postorder.length-1);    return node; } public TreeNode Createtree (int[] inorder,int inbegin,int inend,int[] postorder,int postbegin,int postend) {if (    Inbegin>inend) {return null;    } int root=postorder[postend];    int index=0;    for (int i=inbegin;i<=inend;i++) {if (Root==inorder[i]) {index=i;    Break    }} int len=index-inbegin; TreeNode Left=createtree (inorder, Inbegin, Index-1, PostordeR, Postbegin, postbegin+len-1);    TreeNode Right=createtree (inorder, index+1, Inend, Postorder, Postbegin+len, postend-1);    TreeNode node=new TreeNode (root);    Node.left=left;    Node.right=right;    return node; }}}


Construct Binary Tree from inorder and Postorder traversal

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.