import java.util.*;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private Map<Integer, Integer> map = new HashMap<>();
public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
if(pre == null || pre.length == 0) {
return null;
} else if(pre.length == 1) {
return new TreeNode(pre[0]);
}
for(int i = 0; i < pre.length; i++) {
map.put(vin[i], i);
}
return buildTree(pre, vin, 0, pre.length - 1, 0, pre.length - 1);
}
public TreeNode buildTree(int[] pre, int[] vin, int prLe, int prRi, int viLe, int viRi) {
if(prLe > prRi) {
return null;
}
int viRoot = map.get(pre[prLe]);
int leLen = viRoot - viLe;
TreeNode root = new TreeNode(pre[prLe]);
root.left = buildTree(pre, vin, prLe + 1, prLe + leLen, viLe, viRoot - 1);
root.right = buildTree(pre, vin, prLe + leLen + 1, prRi, viRoot + 1, viRi);
return root;
}
}