/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
TreeNode t = refuction(pre,0,pre.length-1,in,0,in.length-1);
return t;
}
private TreeNode refuction(int [] pre, int preStart,int preEnd,int [] in,int inStart,int inEnd){
if (preStart > preEnd || inStart > inEnd) return null;
TreeNode root = new TreeNode(pre[preStart]);
for(int i = inStart;i <= inEnd;i++){
if(in[i] == pre[preStart]){
//前序遍历首个节点为二叉树的根节点,找到在中序遍历根节点的位置,则左边为左子树,右边为右子树。
root.left = refuction(pre,preStart+1,preStart+(i-inStart),in,inStart,i-1 );
root.right = refuction(pre,preStart+(i-inStart)+1,preEnd,in,i+1,inEnd);
break;
}
}
return root;
}
}