public TreeNode reconstruct(int[] in, int[] level) {
if (in.length == 0) {
return null;
}
Map<Integer, Integer> hashmap = new HashMap<>();
List<Integer> levell = new ArrayList<>();
for (int i = 0; i < in.length; i++) {
hashmap.put(in[i], i);
levell.add(level[i]);
}
return build(in, 0, in.length - 1, levell, hashmap);
}
private TreeNode build(int[] in, int instart, int inend, List<Integer> level, Map<Integer, Integer> hashmap) {
if (instart > inend) {
return null;
}
TreeNode root = new TreeNode(level.get(0));
// int position = find(inorder, instart, inend, post[postend]);
List<Integer> left = new ArrayList<>();
List<Integer> right = new ArrayList<>();
int position = hashmap.get(level.get(0));
for (int i = 1; i < level.size(); i++) {
int num = level.get(i);
int pos = hashmap.get(num);
if (pos < position) {
left.add(num);
} else {
right.add(num);
}
}
root.left = build(in, instart, position - 1, left, hashmap);
root.right = build(in, position + 1, inend, right, hashmap);
return root;
}