根据前序和中序构造二叉树-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();
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值