简单介绍一下思想,先看前序,前序遍历的第一个节点,就是该树的根。在中序中找到该根的位置,设为index,在中序遍历集合中,位于index之前的属于根的左子树,位于index之后的属于根的右子树。然后,对左右子数,遍历的调用该过程,就能将树结构还原。之后后序遍历也就不是问题了。
public class M {
public static class Tree{
public int value;
public Tree left;
public Tree right;
public Tree(int value) {
this.value=value;
}
}
public static void main(String[] args){
int[]preOrder={1,2,4,5,3,6,7};
int[]midOrder={4,2,5,1,6,3,7};
getBehindOrder(preOrder, midOrder);
}
public static void getBehindOrder(int[]pre,int[]mid){
if (pre==null||mid==null||pre.length!=mid.length) {
return;
}
Tree root=buildTree(pre, mid);
behindOrder(root);
}
public static void behindOrder(Tree root){//后序遍历二叉树
if (root==null) {
return;
}
if (root.left!=null) {
behindOrder(root.left);
}
if (root.right!=null) {
behindOrder(root.right);
}
System.o