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();
}
}
根据前序和中序构造二叉树-java版
最新推荐文章于 2024-09-06 00:15:00 发布