題目描述:輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
java代碼:
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class RebuildTreeByPreAndMid {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre==null||in==null||pre.length==0||in.length==0){
return null;
}
return f(pre,in,0,pre.length-1,0,in.length-1);
}
public TreeNode f(int [] pre,int [] mid,int pStart,int pEnd,int mStart,int mEnd){
if(pStart>pEnd||mStart>mEnd){
return null;
}
TreeNode p=new TreeNode(pre[pStart]);
int pos=-1; // 找出根節點所在位置,從而確定左右子孫的範圍
for(int i=mStart;i<=mEnd;i++){
if(mid[i]==pre[pStart]){
pos=i;
break;
}
}
p.left=f(pre,mid,pStart+1,pEnd,mStart,pos-1);
p.right=f(pre,mid,pStart+pos-mStart+1,pEnd,pos+1,mEnd);
return p;
}
// 前序遍歷檢驗
public void preOrder(TreeNode head){
if(head!=null){
System.out.print(head.val+" ");
preOrder(head.left);
preOrder(head.right);
}else{
return;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
RebuildTreeByPreAndMid test= new RebuildTreeByPreAndMid();
int pre[]={1,2,4,7,3,5,6,8};
int in[]={4,7,2,1,5,3,8,6};
TreeNode head=test.reConstructBinaryTree(pre, in);
test.preOrder(head);
}
}