Similar to the most popular post but without constructing a helper function.

```
public TreeNode buildTree(int[] preorder, int[] inorder) {
int n = preorder.length;
// Base case.
if(n == 0) {
return null;
}
// General case.
int rootVal = preorder[0];
int rootIndex = 0;
TreeNode root = new TreeNode(rootVal);
for(int i = 0; i < n; i++) {
if(inorder[i] == rootVal) {
rootIndex = i;
break;
}
}
int leftLength = rootIndex;
int rightLength = n - 1 - leftLength;
root.left = buildTree(Arrays.copyOfRange(preorder, 1, 1 + leftLength), Arrays.copyOfRange(inorder, 0, leftLength));
root.right = buildTree(Arrays.copyOfRange(preorder, 1 + leftLength, n), Arrays.copyOfRange(inorder, rootIndex + 1, n));
return root;
}
```