/**
* Definition for a binary tree node.
* class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] pre, int[] in) {
if(pre.length == 0 || in.length == 0 || pre.length != in.length) {
return null;
}
// 拿到根结点
TreeNode root = new TreeNode(pre[0]);
// 找的根结点在中序遍历中的位置
int i = 0;
while(in[i] != root.val) {
i++;
}
//确定左子树前序遍历长度
int[] preLeft = new int[i];
//确定左子树中序遍历长度
int[] inLeft = new int[i];
//确定右子树前序遍历长度
int[] preRight = new int[in.length - i -1];
//确定右子树中序遍历长度
int[] inRight = new int[in.length - i -1];
// 遍历 依次拿到左右子树 前中序遍历的值
for(int j = 0 ; j<in.length ;j++) {
if(j < i) {
preLeft[j] = pre[j+1];
inLeft[j] = in[j];
}else if(j > i) {
preRight[j-i-1] = pre[j];
inRight[j-i-1] = in[j];
}
}
// 递归
root.left = buildTree(preLeft,inLeft);
root.right = buildTree(preRight,inRight);
return root;
}
}