**
题目: 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字
**
public static TreeNode construct(int[] preorder,int[] inorder){
if(preorder == null || inorder == null){
return null;
}
return constructCore(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
private static TreeNode constructCore(int[] preorder, int startPre, int endPre, int[] inorder, int startIn, int endIn) {
if(startPre < endPre || startIn < endIn){
return null;
}
TreeNode root = new TreeNode(startPre);
for(int i = startIn ; i < endIn ; i++){
if(preorder[startPre] == inorder[i]){
//找到之后,分别对左子树和右子树进行递归算法,重复此步骤
root.lchild= constructCore(preorder,startPre+1,startPre+i-startIn,inorder,startIn,i-1);
root.rchild = constructCore(preorder,startPre+i-startIn+1,endPre,inorder,i+1,endIn);
break;
}
}
return root;
}
***帅气的远远啊***