# Leetcode-Construct binary tree from inorder and postorder Traversal

Source: Internet
Author: User

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

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

`/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */struct TreeNode{int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public:    TreeNode *buildTree(std::vector<int> &inorder, std::vector<int> &postorder) {return buildBinTree(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);}private:TreeNode *buildBinTree(std::vector<int> &inorder,int inStart,int inEnd,std::vector<int> &postorder,int postStart,int postEnd){if(inStart > inEnd || postStart > postEnd) return NULL;TreeNode *root = new TreeNode(postorder[postEnd]);int rootIndex = 0;for (int i = inStart; i <= inEnd; i++){if(inorder[i] == root->val){rootIndex = i;break;}}int len = rootIndex - inStart;root->left = buildBinTree(inorder,inStart,rootIndex-1,postorder,postStart,postStart+len-1);root->right= buildBinTree(inorder,rootIndex+1,inEnd,postorder,postStart+len,postEnd-1);return root;}};`

Leetcode-Construct binary tree from inorder and postorder Traversal

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.