# 重建二叉树

1）知道一颗二叉树的前序和中序序列可以唯一确定一棵二叉树
2）递归，对数组分成一段一段的

1）给定的序列不能含有重复的数字
2）给定的序列必须是正确的正确的序列

1）就是比较常见的，传递数组引用

/**
* 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 [] in) {
if(pre == null || in == null || pre.length == 0 || in.length == 0 || (pre.length != in.length)) {
return null;
}
TreeNode root = createBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
return root;
}

public TreeNode createBinaryTree(int [] pre, int preSta, int preEnd, int [] in, int inSta, int inEnd) {
if(preSta > preEnd || inSta > inEnd) {
return null;
}
TreeNode treeNode = new TreeNode(pre[preSta]);
int i = 0;
for(; i < in.length; i++) {
if(pre[preSta] == in[i]) {
break;
}
}
treeNode.left = createBinaryTree(pre, preSta + 1, preSta + i - inSta, in, inSta, i - 1);
treeNode.right = createBinaryTree(pre, preSta + i - inSta+1, preEnd, in, i + 1, inEnd);
return treeNode;
}
}

1）是native methods 非java编码写的，是C写的
2）[from, to) ;
3) 不管有没有复制元素，都会得到一个数组的引用

public static void main(String[] args) {
int[] a = {1};
int[] b = Arrays.copyOfRange(a, 1, 1);
if(b == null) {
System.out.println("b is null");
} else {
// 执行这个分支 输出 0
System.out.println(b.length);
}
}

public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre.length == 0||in.length == 0){
return null;
}
TreeNode node = new TreeNode(pre[0]);
for(int i = 0; i < in.length; i++){
if(pre[0] == in[i]){
node.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i+1), Arrays.copyOfRange(in, 0, i));
node.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i+1, pre.length), Arrays.copyOfRange(in, i+1,in.length));
break;
}
}
return node;
}
}