import java.util.*;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre, int [] vin) {
if (pre.length == 0) {
return null;
}
if (pre.length == 1) {
return new TreeNode(pre[0]);
}
if (pre.length == 2) {
TreeNode root = new TreeNode(pre[0]);
if (pre[0] == vin[0]) {
root.right = new TreeNode(vin[1]);
} else {
root.left = new TreeNode(vin[0]);
}
return root;
}
int rootVal = pre[0];
int rootIndex = 0;
for (int i = 0; i < vin.length; i++) {
if (vin[i] == rootVal) {
rootIndex = i;
break;
}
}
TreeNode root = new TreeNode(rootVal);
if (rootIndex == 0) {
int[] rightVin = Arrays.copyOfRange(vin, 1, vin.length);
Map<Integer, Integer> map = new HashMap<>();
for (int i : rightVin) {
map.put(i, 0);
}
int endIndex = 0;
for (int j = 0; j < pre.length; j++) {
if (map.containsKey(pre[j])) {
endIndex = j;
}
}
int[] rightPre = Arrays.copyOfRange(pre, 1, endIndex + 1);
root.right = reConstructBinaryTree(rightPre, rightVin);
} else if (rootIndex == 1) {
root.left = new TreeNode(vin[0]);
int[] rightVin = Arrays.copyOfRange(vin, 2, vin.length);
Map<Integer, Integer> map = new HashMap<>();
for (int i : rightVin) {
map.put(i, 0);
}
int endIndex = 0;
for (int j = 0; j < pre.length; j++) {
if (map.containsKey(pre[j])) {
endIndex = j;
}
}
int[] rightPre = Arrays.copyOfRange(pre, 2, endIndex + 1);
root.right = reConstructBinaryTree(rightPre, rightVin);
} else if (rootIndex == vin.length - 1) {
int[] leftVin = Arrays.copyOfRange(vin, 0, vin.length - 1);
Map<Integer, Integer> map = new HashMap<>();
for (int i : leftVin) {
map.put(i, 0);
}
int endIndex = 0;
for (int j = 0; j < pre.length; j++) {
if (map.containsKey(pre[j])) {
endIndex = j;
}
}
int[] leftPre = Arrays.copyOfRange(pre, 1, endIndex + 1);
root.left = reConstructBinaryTree(leftPre, leftVin);
} else if (rootIndex == vin.length - 2) {
root.right = new TreeNode(vin[vin.length - 1]);
int[] leftVin = Arrays.copyOfRange(vin, 0, vin.length - 2);
Map<Integer, Integer> map = new HashMap<>();
for (int i : leftVin) {
map.put(i, 0);
}
int endIndex = 0;
for (int j = 0; j < pre.length; j++) {
if (map.containsKey(pre[j])) {
endIndex = j;
}
}
int[] leftPre = Arrays.copyOfRange(pre, 1, endIndex + 1);
root.left = reConstructBinaryTree(leftPre, leftVin);
} else {
int[] leftVin = Arrays.copyOfRange(vin, 0, rootIndex);
int[] rightVin = Arrays.copyOfRange(vin, rootIndex + 1, vin.length);
Map<Integer, Integer> map = new HashMap<>();
for (int i : leftVin) {
map.put(i, 0);
}
int endIndex = 0;
for (int j = 0; j < pre.length; j++) {
if (map.containsKey(pre[j])) {
endIndex = j;
}
}
int[] leftPre = Arrays.copyOfRange(pre, 1, endIndex + 1);
int[] rightPre = Arrays.copyOfRange(pre, endIndex + 1, pre.length);
root.left = reConstructBinaryTree(leftPre, leftVin);
root.right = reConstructBinaryTree(rightPre, rightVin);
}
return root;
}
}