【题目】已知一棵二叉树的所有节点值都不同,给定这棵二叉树正确的先序、中序和后序数组。请分别用三个函数实现任意两种数组结合重构原来的二叉树,并返回重构二叉树的头结点。
public class PreInPostToBST {
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int value) {
this.value = value;
}
}
public static Node preInToTree(int[] pre, int[] in) {
if (pre == null || in == null) {
return null;
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < in.length; i++) {
map.put(in[i], i);
}
return preIn(pre, 0, pre.length - 1, in, 0, in.length - 1, map);
}
public static Node preIn(int[] pre, int pi, int pj, int[] in, int ni, int nj, Map<Integer, Integer> map) {
if (pi > pj) {
return null;
}
Node head = new Node(pre[pi]);
int index = map.get(pre[pi]);
head.left = preIn(pre, pi + 1, pi + index - ni, in, ni, index - 1, map);
head.right = preIn(pre, pi + index - ni + 1, pj, in, index + 1, nj, map);
return head;
}
public static Node posInToTree(int[] pos, int[] in) {
if (pos == null || in == null) {
return null;
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < in.length; i++) {
map.put(in[i], i);
}
return posIn(in, 0, in.length - 1, pos, 0, pos.length - 1, map);
}
public static Node posIn(int[] in, int ni, int nj, int[] pos, int si, int sj, Map<Integer, Integer> map) {
if (si > sj) {
return null;
}
Node head = new Node(pos[sj]);
int index = map.get(pos[sj]);
head.left = posIn(in, ni, index - 1, pos, si, si + index - ni - 1, map);
head.right = posIn(in, index + 1, nj, pos, si + index - ni, sj - 1, map);
return head;
}
public static Node prePosToTree(int[] pre, int[] pos) {
if (pre == null || pos == null) {
return null;
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < pos.length; i++) {
map.put(pos[i], i);
}
return prePos(pre, 0, pre.length - 1, pos, 0, pos.length - 1, map);
}
public static Node prePos(int[] pre, int pi, int pj, int[] pos, int si, int sj, Map<Integer, Integer> map) {
Node head = new Node(pos[sj--]);
if (pi == pj) {
return head;
}
int index = map.get(pre[++pi]);
head.left = prePos(pre, pi, pi + index - si, pos, si, index, map);
head.right = prePos(pre, pi + index - si + 1, pj, pos, index + 1, sj, map);
return head;
}
}