# 根据前序和中序构造二叉树-java版

package offer;
class TreeNode{
public int value;
public TreeNode left;
public TreeNode right;
public TreeNode(int value,TreeNode left,TreeNode right){
this.value = value;
this.left = left;
this.right = right;
}
public void printPre(){
if(this!=null){
System.out.println(this.value);
if(this.left!=null){
this.left.print();
}
if(this.right!=null){
this.right.print();
}
}

}
}
public class Test6 {
public TreeNode construct(int[] preOrder ,int[] inOrder,int len){
if(len<=0||preOrder==null||inOrder==null){
return null;
}
else return constructCore(preOrder,inOrder,len,0,0);
}
public TreeNode constructCore(int[] a,int[] b,int len,int lowa,int lowb){
int rootValue = a[lowa];
TreeNode node = new TreeNode(rootValue,null,null);
if(len==1){
if(a[lowa]==b[lowb]){
return node;
} else
try {
throw new Exception("invalid input");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int i = lowb;
while(i<lowb+len&&b[i]!=rootValue)
i++;
if(i==len+lowb&&b[i]!=rootValue)
try {
throw new Exception("error");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int leftlength = i-lowb;
int rightlength = len-i+lowb-1;
int aLeftStart = lowa+1;
int aRightStart = leftlength+lowa+1;
int bLeftStart = lowb;
int bRightStart = i+1;
if(leftlength>0){
node.left = constructCore(a,b,leftlength,aLeftStart,bLeftStart);
}
if(rightlength>0){
node.right = constructCore(a,b,rightlength,aRightStart,bRightStart);
}
return node;
}
public static void main(String[] args){
Test6 t = new Test6();
int[] a ={1,2,4,7,3,5,6,8};
int[] b ={4,7,2,1,5,3,8,6};
TreeNode t1 = t.construct(a, b, a.length);
t1.printPre();
}
}

04-08 4513

08-30 571

01-09 1669

09-06 260

11-30 1233

#### <em>Java</em>实现二叉树的<em>先序</em>、<em>中序</em>、后续、层次遍历

2018年05月07日 00:00

10-23 999

09-07 1228

04-22 2.5万

10-07 1904