題目:根據某二叉樹的前序遍歷和中序遍歷結果,重建該二叉樹
思路:前序遍歷的第一個數字就是根節點,在中序遍歷中找到根節點,根節點左邊是左子樹節點,根節點右邊是右子樹節點;這樣遞歸構建
public BinaryTreeNode constructCore(int[] pre,int[] in) {
if(pre==null||in==null||pre.length!=in.length) {
return null;
}
return constructCore(pre,in,0,pre.length-1,0,in.length-1);
}
private BinaryTreeNode constructCore(int[] pre,int[] in,int startPre,int endPre,int startIn,int endIn) {
//根節點是前序遍歷第一個元素
BinaryTreeNode root=new BinaryTreeNode(pre[startPre]);
//在中序遍歷中找到根節點
int rootIn=startIn;
while(in[rootIn]!=pre[startPre]&&rootIn<endIn) {
rootIn++;
}
int length=rootIn-startIn;
//構建左子樹
if(length>0) {
root.left=constructCore(pre,in,startPre+1,startPre+length,startIn,rootIn-1);
}
//構建右子樹
if(length<endPre-startPre) {
root.right=constructCore(pre,in,startPre+length+1,endPre,rootIn+1,endIn);
}
//返回根節點
return root;
}