# LeetCode题目：Construct Binary Tree from Inorder and Postorder Traversal

By | 2012 年 12 月 12 日

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.

```/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *buildTree(vector &iorder, int isi, int iei, vector &porder, int psi, int pei) {
if(iei - isi < 0 || iei - isi != pei - psi) {
return NULL;
}
//the porder[pei] is the root of this tree
TreeNode *root = new TreeNode(porder[pei]);
//find the root in the iorder to seperate it into left sub tree and right sub tree
int riii = -1;//root index in inorder array
for(int i = isi; i <= iei; ++i) {
if(iorder[i] == root->val) {
riii = i;
break;
}
}
if(riii == -1) return root;//error
int lnodes = riii - isi;
//for the left sub tree
//the isi to riii - 1 in inorder array will be it's inorder traversal
//and the psi to psi + lnodes - 1 in postorder array will be it's post order traversal
root->left = buildTree(iorder, isi, riii - 1, porder, psi, psi + lnodes - 1);
//for the right sub tree is similary to the left
root->right = buildTree(iorder, riii + 1, iei, porder, psi + lnodes, pei - 1);
return root;
}
TreeNode *buildTree(vector &inorder, vector &postorder) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() -1);
}
};
```

## 4 thoughts on “LeetCode题目：Construct Binary Tree from Inorder and Postorder Traversal”

1. uniEagle Post author

没啥好思路，只想到可以用一个队列一层一层做，或者用一个堆栈将递归展开。