import java.util.HashMap;
class Solution {
private int postorderIndex;
private HashMap<Integer, Integer> inorderIndexMap;
public TreeNode buildTree(int[] inorder, int[] postorder) {
// Initialize postorder index to the last element
postorderIndex = postorder.length - 1;
// 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(postorder, 0, inorder.length - 1);
}
private TreeNode buildSubtree(int[] postorder, int left, int right) {
if (left > right) {
return null; // Base case: no elements to construct the tree
}
// Get the current root value from postorder
int rootValue = postorder[postorderIndex--];
TreeNode root = new TreeNode(rootValue);
// Find the index of the root value in the inorder array
int inorderIndex = inorderIndexMap.get(rootValue);
// Recursively construct the right and left subtrees
root.right = buildSubtree(postorder, inorderIndex + 1, right);
root.left = buildSubtree(postorder, left, inorderIndex - 1);
return root;
}
}