Construct Binary Tree from Inorder and Postorder Traversal, inorderpostorder

Source: Internet
Author: User

Construct Binary Tree from Inorder and Postorder Traversal, inorderpostorder

The original question is as follows;

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

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

The meaning is simple: generate a tree based on the ordinal traversal and the ordinal traversal.


The idea is simple: determine the root node based on the Post-order traversal sequence, locate the root node in the middle-order traversal, and divide the original sequence into two parts, recursion solves this problem by solving the Left and Right Parts.

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: recursion */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) {return 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 ;}}}


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.