题目链接
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/5d8a0ce2061a45cab7c948d5bdfd99f8.png)
递归
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length == 0 || inorder.length == 0){
return null;
}
return buildHelper(preorder, 0, preorder.length, inorder, 0, inorder.length);
}
public TreeNode buildHelper(int[] preorder, int preorderStart, int preorderEnd, int[] inorder, int inorderStart, int inorderEnd){
if(preorderStart == preorderEnd){
return null;
}
int rootVal = preorder[preorderStart];
TreeNode root = new TreeNode(rootVal);
int middleIndex;
for(middleIndex = inorderStart; middleIndex < inorderEnd; middleIndex++){
if(inorder[middleIndex] == rootVal){
break;
}
}
int leftInorderStart = inorderStart;
int leftInorderEnd = middleIndex;
int rightInorderStart = middleIndex + 1;
int rightInorderEnd = inorderEnd;
int leftPreorderStart = preorderStart + 1;
int leftPreorderEnd = preorderStart + 1 + middleIndex - inorderStart;
int rightPreorderStart = preorderStart + 1 + middleIndex - inorderStart;
int rightPreorderEnd = preorderEnd;
root.left = buildHelper(preorder, leftPreorderStart, leftPreorderEnd , inorder, leftInorderStart, leftInorderEnd);
root.right = buildHelper(preorder,rightPreorderStart, rightPreorderEnd, inorder, rightInorderStart, rightInorderEnd);
return root;
}
}