递归核心点:
1、问题能够分解成规模更小,但是解法一样子问题。
2、要有递归结束条件。
import java.util.Arrays;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
//这个是递归结束条件,后面两个排除第一次传进来的数组有空数组的情况
if(pre.length==0 || in.length==0 || pre==null || in==null){
return null;
}
//拿到根节点
TreeNode root=new TreeNode(pre[0]);
//这里为什么能这样?因为题目说了二叉树里面不含有重复的数字
for(int i=0;i<in.length;i++){
if(in[i]==pre[0]){
root.left=reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),Arrays.copyOfRange(in,0,i));
root.right=reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),Arrays.copyOfRange(in,i+1,in.length));
break;
}
}
return root;
}
}