import java.util.HashMap;
class Solution {
private int preorderIndex = 0;
private HashMap<Integer, Integer> inorderIndexMap;
public TreeNode buildTree(int[] preorder, int[] inorder) {
// Create a map to store the index of each value in the inorder array
inorderIndexMap = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
inorderIndexMap.put(inorder[i], i);
}
return buildSubtree(preorder, 0, inorder.length - 1);
}
private TreeNode buildSubtree(int[] preorder, int left, int right) {
if (left > right) {
return null; // Base case: no elements to construct the tree
}
// Get the current root value from preorder
int rootValue = preorder[preorderIndex++];
TreeNode root = new TreeNode(rootValue);
// Find the index of the root value in the inorder array
int inorderIndex = inorderIndexMap.get(rootValue);
// Recursively construct the left and right subtrees
root.left = buildSubtree(preorder, left, inorderIndex - 1);
root.right = buildSubtree(preorder, inorderIndex + 1, right);
return root;
}
}