class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return buildTree(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1);
}
public TreeNode buildTree(int[] preorder, int prS, int prE, int[] inorder, int inS, int inE) {
if (inS > inE)
return null;
int rootVal = preorder[prS];
int rootIdx = -1;
for (int i = inS; i <= inE; i++) {
if (inorder[i] == rootVal) {
rootIdx = i;
break;
}
}
TreeNode root = new TreeNode(rootVal);
int inLS = inS;
int inLE = rootIdx - 1;
int prLS = prS + 1;
int prLE = (inLE - inLS + prLS);
int prRS = prLE + 1;
int prRE = prE;
int inRS = rootIdx + 1;
int inRE = inE;
root.left = buildTree(preorder, prLS, prLE, inorder, inLS, inLE);
root.right = buildTree(preorder, prRS, prRE, inorder, inRS, inRE);
return root;
}
}