##先序与中序:
public class ReBuildBinaryTree{
public static void main(String[] args) {
int[] pre={1,2,4,7,3,5,6,8};
int[] mid={4,7,2,1,5,3,8,6};
Node root=rebuild(pre, mid);
show(root);
}
//思想:利用先序遍历对中序遍历分割
public static Node rebuild(int[] pre,int[] mid){
if(pre==null||mid==null||pre.length!=mid.length){
return null;
}
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<mid.length;i++){
map.put(mid[i], i);
}
return build(pre,0,pre.length-1,mid,0,mid.length-1,map);
}
private static Node build(int[] pre, int ps, int pe, int[] mid, int ms, int me, HashMap<Integer, Integer> map) {
if(ps>pe){
return null;
}
Node head=new Node();
head.data=pre[ps];
int index=map.get(pre[ps]);
head.left=build(pre, ps+1, index+ps-ms, mid, ms, index-1, map);
head.right=build(pre,index+ps-ms+1, pe, mid, index+1, me, map);
//中序与后序恢复二叉树
//head.left=build(mid,ms,index-1,pos,ps,ps+index-ms-1,map);
//head.right=build(mid,index+1,me,pos,ps+index-ms,pe-1,map);
return head;
}
private static class Node{
int data;
Node left,right;
}
public static void show(Node head){
if(head!=null){
Queue<Node> queue=new LinkedList<Node>();
queue.offer(head);
while(!queue.isEmpty()){
head=queue.poll();
System.out.print(head.data+" ");
if(head.left!=null){
queue.offer(head.left);
}
if(head.right!=null){
queue.offer(head.right);
}
}
}
}
}