1.理论部分知识
2.中后序构建树的代码实现
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class In_Post {
public TreeNode reConstructBinaryTree(int[] in, int[] post) {//post是后序遍历数组,in是中序遍历数组
int len = post.length;
TreeNode root = new TreeNode(post[len - 1]); //根据后序遍历顺序,最后一个节点为根节点
if (len == 1) {
root.left = null;
root.right = null;
return root;
}
int flag = 0;
for (int i = 0; i < len; i++) { //在中序遍历结果中找到根节点
if (in[i] == post[len - 1]) {
flag = i;
break;
}
}
//如果存在左子树
if (flag > 0) {
int[] leftIn = new int[flag];
int[] leftPost = new int[flag];
for (int j = 0; j < flag; j++) {
leftIn[j] = in[j];
}
for (int j = 0; j < flag; j++) {
leftPost[j] = post[j];
}
root.left = reConstructBinaryTree(leftIn, leftPost);
} else {
root.left = null;
}
//如果存在右子树
if (len - 1 - flag > 0) {
int[] rightIn = new int[len - 1 - flag];
int[] rightPost = new int[len - 1 - flag];
for (int j = 1 + flag; j < len; j++) { //中序遍历要去掉当前根节点
rightIn[j - 1 - flag] = in[j];
}
for (int j = flag; j < len - 1; j++) { //后序遍历的根节点在最后,所以开始处为flag,结束点为len - 1
rightPost[j - flag] = post[j];
}
} else {
root.right = null;
}
return root;
}
}