public static <T> BinaryTree<T> BinaryTreeCreate(T[] prelist, T[] inlist) {
BinaryNode<T> root = BinaryTreeCreate(0, inlist.length - 1, 0, prelist, inlist);
return new BinaryTree<>(root);
}
public static <T> BinaryNode<T> BinaryTreeCreate(int left, int right, int pos, T[] prelist, T[] inlist) {
int len = right - left + 1;
T croot = prelist[pos];
BinaryNode<T> node = new BinaryNode<>(croot);
if (len <= 1) {
return node;
}
int mid = Index(inlist, croot, left, right);
if (mid != left) {
node.left = BinaryTreeCreate(left, mid - 1, pos + 1, prelist, inlist);
}
if (mid != right) {
int rpos = pos + mid - left + 1;
node.right = BinaryTreeCreate(mid + 1, right, rpos, prelist, inlist);
}
return node;
}
private static <T> int Index(T[] data, T target, int left, int right) {
for (int j = left; j <= right; j++) {
if (data[j].equals(target)) {
return j;
}
}
return -1;
}
Integer[] PRE_SEQ = { 1, 2, 6, 7, 8, 5, 3, 6, 7, 8 };
Integer[] MID_SEQ = {7, 6, 8, 2, 5, 1, 3, 7, 6, 8 };这个可以构造
但是Integer[] PRE_SEQ = { 6, 2, 6, 7, 8, 5, 3, 6, 7, 8 };
Integer[] MID_SEQ = {7, 6, 8, 2, 5, 6, 3, 7, 6, 8 };构造不了
不知道你在纠结什么,用先跟和中跟结果不能唯一确定一棵二叉树。
比如这样的先根[6, 6, 6, 6, 6, 6, 6, 6] 中根[6, 6, 6, 6, 6, 6, 6, 6] ,你能构造出多少个不同的二叉树?这个歧义是无法消除的。
这种构造方式只是一个练习,是帮助你理解两种遍历方式,肯定要用没有歧义的结果来做,要不然就没有意义了。