1、根据前序遍历序列和中序遍历序列,构造二叉树(或求后序遍历序列);
public Node buildTree(int[] preOrder,int[] inOrder){
Node root=buildTree(preOrder,0,preOrder.length-1,inOrder,0,inOrder.length-1);
return root;
}
private Node buildTree(int[] preOrder,int pstart,int pend,int[] inOrder,int istart,int iend){
if(pstart>pend || istart>iend){
return null;
}
Node root=new Node(preOrder[pstart]);
int index=findIndexInArray(preOrder[pstart],inOrder,istart,iend);
root.left=buildTree(preOrder,pstart+1,pstart+index-istart,inOrder,istart,index-1);
root.right=buildTree(preOrder,pstart+index-istart+1,pend,inOrder,index+1,iend);
return root;
}
private int findIndexInArray(int x, int[] inOrder, int pstart, int pend) {
for(int i=pstart;i<=pend;i++){
if(inOrder[i]==x){
return i;
}
}
return -1;
}
2、根据后序遍历序列和中序遍历序列,构造二叉树(或求前序遍历序列);
public Node buildTree(int[] inOrder,int[] postOrder){
Node root=buildTree(inOrder,0,inOrder.length-1,postOrder,0,postOrder.length-1);
return root;
}
private Node buildTree(int[] inOrder,int istart,int iend,int[] postOrder,int pstart,int pend){
if(pstart>pend || istart>iend){
return null;
}
Node root=new Node(postOrder[pend]);
int index=findIndexInArray(postOrder[pend],inOrder,istart,iend);
root.left=buildTree(inOrder,istart,index-1,postOrder,pstart,pstart+index-istart-1);
root.right=buildTree(inOrder,index+1,iend,postOrder,pstart+index-istart,pend-1);
return root;
}
private int findIndexInArray(int x, int[] inOrder, int istart, int iend) {
for(int i=istart;i<=iend;i++){
if(inOrder[i]==x){
return i;
}
}
return -1;
}