* 树节点
*/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
/**
* 根据前序序列和后序序列构建树
*/
public class Solution {
public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
int index_pre = 0;
int index_in = 0;
int[] pre_left = null;
int[] pre_right = null;
int[] in_left = null;
int[] in_right = null;
TreeNode tn = null;
// 首先找到根节点
if (pre.length > 0) {
// 创建节点
tn = new TreeNode(pre[0]);
tn.left = null;
tn.right = null;
// 找到根节点所在的中序遍历的位置
for (int i = 0; i < in.length; i++) {
if (in[i] == pre[0]) {
index_pre = i;
index_in = i;
break;
}
}
// 判断是否只有一个根节点
if (index_pre != 0) {
// 初始化数组
pre_left = new int[index_pre];
pre_right = new int[pre.length - 1 - index_pre];
in_left = new int[index_in];
in_right = new int[in.length - 1 - index_in];
// 生成新的前序遍历序列以及后序遍历序列
for (int i = 0; i < index_pre; i++) {
pre_left[i] = pre[i + 1];
}
int index_i = pre.length - index_pre - 1;
for (int i = 0; i < index_i; i++) {
pre_right[i] = pre[++index_pre];
}
for (int j = 0; j < index_in; j++) {
in_left[j] = in[j];
}
int index_j = in.length - index_in - 1;
for (int j = 0; j < index_j; j++) {
in_right[j] = in[++index_in];
}
}
} else {
return tn;
}
if (pre_left != null && in_left != null && pre_right != null
&& in_right != null) {
// 左子树
tn.left = reConstructBinaryTree(pre_left, in_left);
// 右子树
tn.right = reConstructBinaryTree(pre_right, in_right);
}
// 返回节点
return tn;
}
}
public class TreeMain {
static Solution sl = new Solution();
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 tr = sl.reConstructBinaryTree(pre, in);// 生成树构建完毕,利用递归前序,中序或是后序打印即可
}
}