//定义二叉树
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
//重建二叉树
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
//建立根节点
TreeNode treeNode=new TreeNode(pre[0]);
//找到中序遍历中根节点的位置i
int rootIndex=0;
for(int i=0;i<in.length;i++){
if(pre[0]==in[i]){
rootIndex=i;
}
}
//将前序遍历左右树分为两个数组
int[] preLeft=new int[rootIndex];
int[] preRight=new int[pre.length-rootIndex-1];
for(int i=0;i<rootIndex;i++){
preLeft[i]=pre[i+1];
}
for(int i=0;i<pre.length-rootIndex-1;i++){
preRight[i]=pre[rootIndex+i+1];
}
//将中序遍历的树分为左右节点
int[] midLeft=new int[rootIndex];
int[] midRight=new int[in.length-rootIndex-1];
for(int i=0;i<rootIndex;i++){
midLeft[i]=in[i];
}
for(int i=0;i<pre.length-rootIndex-1;i++){
midRight[i]=in[rootIndex+i+1];
}
//通过循环将重建左右树
if(pre.length>0&in.length>0){
if(preLeft.length>0){
treeNode.left=reConstructBinaryTree(preLeft,midLeft);
}
if(preRight.length>0){
treeNode.right=reConstructBinaryTree(preRight,midRight);
}
}
return treeNode;
}
}