/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
*@param preorder : A list of integers that preorder traversal of a tree
*@param inorder : A list of integers that inorder traversal of a tree
*@return : Root of a tree
*/
public TreeNode buildTree(int[] preorder, int[] inorder) {
// write your code here
TreeNode root=null;
root=preAndIn(preorder, inorder);
return root;
}
private static TreeNode preAndIn(int []preorder,int []inorder){
if(inorder.length==0&&preorder.length==0){
return null;
}
int val=preorder[0];
TreeNode root=new TreeNode(val);
int index=0;
for(int i=0;i<inorder.length;i++){
if(val==inorder[i]){
index=i;
}
}
int leftInOrder[]=Arrays.copyOfRange(inorder, 0, index);
int rightInOrder[]=Arrays.copyOfRange(inorder, index+1, inorder.length);
int leftPreOrder[]=Arrays.copyOfRange(preorder, 1, leftInOrder.length+1);
int rightPreOrder[]=Arrays.copyOfRange(preorder, index+1, preorder.length);
root.left=preAndIn(leftPreOrder, leftInOrder );
root.right=preAndIn(rightPreOrder, rightInOrder);
return root;
}
}