# 重建二叉树(Java)

import java.util.HashMap;
import java.util.Map;

public class ReConstructBinaryTree {
//用来缓存中序遍历数组的每个值对应的索引
private static Map<Integer, Integer> inOrderNumsIdx = new HashMap<>();

public static TreeNode reConstructBinaryTree(int[] pre,int[] in) {
for(int i = 0; i < in.length; i++){
inOrderNumsIdx.put(in[i], i);
}
return reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);

}

public static TreeNode reConstructBinaryTree(int[] pre, int preL, int preR,int[] in,int inL, int inR) {
if (preL == preR) {
return new TreeNode(pre[preL]);
}
if (preL > preR || inL > inR) {
return null;
}
TreeNode root = new TreeNode(pre[preL]);
int inIdx = inOrderNumsIdx.get(root.val);//inOrder中根节点对应的索引
int leftTreeSize = inIdx - inL;
root.left = reConstructBinaryTree(pre, preL + 1, preL + leftTreeSize, in, inL, inL + leftTreeSize - 1);
root.right = reConstructBinaryTree(pre, preL + leftTreeSize + 1, preR, in, inL + leftTreeSize + 1, inR);
return root;

}
public static void main(String[] args) {
int[] pre = {1,2,4,7,3,5,6,8};
int[] in = {4,7,2,1,5,3,8,6};
TreeNode tree = new TreeNode(0);
tree = reConstructBinaryTree(pre, in);
}
}

public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}