```
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length == 0) {
return null;
}
return buildTreeHelper(preorder, inorder, 0, preorder.length-1, 0, preorder.length-1);
}
public TreeNode buildTreeHelper(int[] preorder, int[] inorder, int ps, int pe, int is, int ie) {
if (ps > pe || is > ie) {
return null;
}
TreeNode root = new TreeNode(preorder[ps]);
if (ps == pe) {
return root;
}
int index = 0;
for (int i=is; i<=ie; i++) {
if (root.val == inorder[i]) {
index = i;
break;
}
}
root.left = buildTreeHelper(preorder, inorder, ps+1, ps+index-is, is, index-1);
root.right = buildTreeHelper(preorder, inorder, ps+index-is+1, pe, index+1, ie);
return root;
}
}
```