package com.offer;

public class 重建二叉树 {
	public class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;
		TreeNode(int x) {
			val = x;
		}
	}
	
	public TreeNode reConstructBinaryTree(int [] p,int [] in){
		if(p.length <= 0 || p == null || in.length <= 0 || in == null){
			return null;
		}
		return construct(p,0,p.length-1,in,0,in.length-1);
	}

	private TreeNode construct(int[] p, int ps, int pe, int[] in, int is, int ie) {
		if(ps>pe || is>ie)
			return null;
		//先序遍历的root是第一个  p[ps]
		int rootval = p[ps];
		int index = is ;
		//在中序遍历中找到root的位置
		while(rootval != in[index] && index <= ie){
			index ++;
		}
		if(index > ie){
			throw new RuntimeException("Invalid Iuput!");
		}
		TreeNode node = new TreeNode(rootval);
		
		//构建左子树
		 node.left = construct(p,ps+1,ps+index-is,in,is,index-1);
		//构建右子树
		 node.right = construct(p,ps+index-is+1,pe,in,index+1,ie);
		return node;
	}
	
	public void print(TreeNode node){
		if(node != null){
			System.out.print(node.val+",");
			print(node.left);
			print(node.right);
		}
	}
	public static void main(String[] args) {
		int []  p = new int[]{1,2,3,4,5,6,7};
		int [] in = new int[]{3,2,4,1,6,5,7};
		重建二叉树 重建二叉树 = new 重建二叉树();
		TreeNode reConstructBinaryTree = 重建二叉树.reConstructBinaryTree(p, in);
		重建二叉树.print(reConstructBinaryTree);
	}
}