public class ReConstructBinaryTree {
public TreeNode reConstructBinaryTree(int[] pre,int[] in) {
TreeNode p = null;
int n = pre.length;
int[] presub; //用来存放前序排序的左右子树
int[] insub; //用来存放中序排序的左右子树
int first = 0;
int k = 0;
if(n>0){
first = pre[0];
p = new TreeNode(first); //p代表的是根节点
for(int i=0;i<n;i++) {
if(in[i] == first) {
k = i;
break;
}
}
presub = new int [k];
insub = new int [k];
presub[i] = pre[i+1];
insub[i] = in[i];
}
p.left = reConstructBinaryTree(presub, insub);
presub = new int [n-k-1];
insub = new int [n-k-1];
for(int i=0;i<n-k-1;i++){
presub[i] = pre[k+i+1];
insub[i] = in[k+i+1];
}
p.right = reConstructBinaryTree(presub, insub);
}
return p;
}
/*实现后序遍历*/
public void postorder(TreeNode p) {if(p != null) {
postorder(p.left);
postorder(p.right);
System.out.print(p.val + " ");
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] prestr = {1,2,3,4,5,6,7,8};
int[] instr = {3,2,4,1,6,5,7,8};
ReConstructBinaryTree ar = new ReConstructBinaryTree();
TreeNode tree = ar.reConstructBinaryTree(prestr, instr);
//ar.printTree(tree);
ar.postorder(tree);
}
}