2021/05/04
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (postorder.length == 0) return null;
int rootVal = postorder[postorder.length - 1];
int p = indexOf(inorder, rootVal);
int[] leftInorder = Arrays.copyOfRange(inorder, 0, p);
int[] rightInorder = Arrays.copyOfRange(inorder, p + 1, inorder.length);
int[] leftPreorder = Arrays.copyOfRange(postorder, 0, p);
int[] rightPreorder = Arrays.copyOfRange(postorder, p, postorder.length - 1);
TreeNode root = new TreeNode(rootVal);
root.left = buildTree(leftInorder, leftPreorder);
root.right = buildTree(rightInorder, rightPreorder);
return root;
}
int indexOf(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) return i;
}
return -1;
}
}