题目链接
递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
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++){
// rootval
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;
}
}