import java.util.*;
/**
* 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 [] vin) {
return func(pre,vin,0,pre.length-1,0,vin.length-1);
}
public TreeNode func(int[] pre,int[] in,int left_pre,int right_pre,int left_in,int right_in){
if(left_pre>=pre.length||left_in>=in.length||left_pre>right_pre||left_in>right_in)
return null;
int value = pre[left_pre];
TreeNode node = new TreeNode(value);
//确定根结点 即node本身
//根结点的value是先序遍历中的最左端的那个
// pre: [1] [2 4 7] [3 5 6 8]
// in : [4 7 2] [1] [5 3 8 6]
int count = left_in;
//在中序遍历中寻找count的位置并且计算长度
while(in[count] != value){
count++;
}//注意count不是从0开始的,而是从left_pre开始的
//找到位置以后计算长度
//比如针对247分析:
/*
pre:[1] 2 4 7 3 5 6 8
in: 4 7 2[1]5 3 8 6
0 1 2 3 4 5 6 7
*/
count = count-left_in;//count为长度
node.left = func(pre,in,left_pre+1,left_pre+count,left_in,right_in+count-1);
node.right = func(pre,in,left_pre+count+1,right_pre,left_in+count+1,right_in);
return node;
}
}