Someone shows us a similar solution in the problem of Construct Binary Tree from Inorder and Postorder Traversal. I just modified his/her solution to fit this problem. The solution is very smart but also not easy to understand. But, it runs fast.

```
int pInorder;
int pPostorder;
public TreeNode buildTree(int[] preorder, int[] inorder) {
pInorder = 0;
pPostorder = 0;
return buildTreeHelper(preorder, inorder, null);
}
public TreeNode buildTreeHelper(int[] preorder, int[] inorder, TreeNode end) {
if (pPostorder >= preorder.length)
return null;
TreeNode n = new TreeNode(preorder[pPostorder++]);
// left subtree exists
if (inorder[pInorder] != n.val) {
n.left = buildTreeHelper(preorder, inorder, n);
}
pInorder++;
// right subtree exists
if ((end == null) || (pInorder < inorder.length && inorder[pInorder] != end.val)) {
n.right = buildTreeHelper(preorder, inorder, end);
}
return n;
}
```