package offer_algorithms;
public class ConstructBT {
//根据前序和中序构建二叉树
public static void main(String[] args) {
int[] pre = new int[]{1, 2, 4, 7, 3, 5, 6, 8};
int[] in = new int[]{4, 7, 2, 1, 5, 3,6, 8};
ConstructBT c = new ConstructBT();
Node t = c.trConstructBT(pre, in);
}
/**
* @param preData 前序遍历数据
* @param inData 中序遍历数据
*/
public Node trConstructBT(int[] preData, int[] inData) {
if (preData == null || inData == null || preData.length == 0 || inData.length == 0) {
return null;//特殊输入
}
if (preData.length == 1 && inData.length == 1) {
return new Node(preData[0]);
}
//根据先序序列获得根结点值
int root = preData[0];
Node tree = new Node(root);
//在中序序列中找到root的位置,然后分开左右子树
int rootIndex = -1;
for (int i = 0; i < inData.length; i++) {
if (inData[i] == root) {
rootIndex = i;
break;
}
}
int right_len = inData.length - rootIndex -1;//将中序序列根据root分开
//此时新的前序,和后序分别放出来了
int[] left_pre = new int[rootIndex];
int[] left_in = new int[rootIndex];
int[] right_pre = new int[right_len];
int[] right_in = new int[right_len];
for (int i = 1; i < rootIndex + 1; i++) {
left_pre[i - 1] = preData[i];
left_in[i - 1] = inData[i - 1];
}
for (int i = rootIndex + 1; i < preData.length; i++) {
right_pre[i - rootIndex - 1] = preData[i];
right_in[i - rootIndex - 1] = inData[i];
}
tree.left = trConstructBT(left_pre, left_in);
tree.right = trConstructBT(right_pre, right_in);
return tree;
}
class Node {
private int data;
private Node left;
private Node right;
public Node(int data) {
this.data = data;
}
}
}