关闭

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

390人阅读 评论(0) 收藏 举报
分类:
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
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:819次
    • 积分:39
    • 等级:
    • 排名:千里之外
    • 原创:3篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档