直接冲代码
package algorithm_tree;
import java.util.Arrays;
/**
* @Author: xc
* @Date: 2019/11/12 20:26
* @Description:
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
*
* TreeNode(int x) {
* val = x;
* }
*}
**/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
// List<Object> preList = Arrays.stream(pre).boxed().collect(Collectors.toList());
// List<Object> inList = Arrays.stream(in).boxed().collect(Collectors.toList());
// int firstIndex = 0;
// for(int i = 0;i<inList.size();i++){
// if (preList.get(0) ==inList.get(i) ){
// firstIndex = i;
// break;
// }
// }
// List left = inList.subList(0,firstIndex);
// List right = inList.subList(firstIndex+1,inList.size());
// preList.remove(0);
// TreeNode node = new TreeNode((Integer)inList.get(firstIndex));
// /*遍历左子树*/
// TreeNode temp = node;
// while(!left.isEmpty()){
//
// }
// /*遍历右子树*/
// temp = node;
// while(!right.isEmpty()){
//
// }
/**
* 重建树,根据原理,从前序遍历的第一个元素值在中序遍历中的值,然后划分左右子树
* 例如:前序遍历序列{1,2,4,7,3,5,6,8} 中序遍历序列{4,7,2,1,5,3,8,6}。
* 那么第一个根节点就是1,中序遍历得到左右子树数组{4,7,2},{5,3,8,6}
* 1
* / \
* {4,7,2} {5,3,8,6}
* 之后再在子树数组中找到根节点以及他的左右子树
* 前序中的1已经用掉了,下一位是2,那么得到{4,7},{}为2的左右子树数组
* 1
* / \
* 2 {5,3,8,6}
* / \
* {4,7} NULL
* 如此直到左右子树数组为空即遍历完了
* 上面注释的方法在遍历左子树和右子树时要不断地创建新的左右子数组,而且需要不断地用到while(子树数组不为空)这个条件
* 于是想到递归*/
if (pre.length==0 || in.length==0) return null;
TreeNode rootNode = new TreeNode(pre[0]);
for (int i = 0;i<in.length;i++){
if (pre[0] == in[i]){
/*这个copyOfRange是左闭右开的,要注意取值*/
int[] left = Arrays.copyOfRange(in,0,i);
int[] right = Arrays.copyOfRange(in,i+1,in.length);
rootNode.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),left);
rootNode.right = reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),right);
}
}
return rootNode;
}
}