题目
import java.util.*;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
//对于数组的操纵
//Arrays.copyOfRange(int[],index,index);
//针对特殊情况来看,直接返回,其实也是递归函数的返回
int num=pre.length;
if(pre.length==0)return null;
TreeNode root=new TreeNode(pre[0]);
int index=0;
for(int i=0;i<pre.length;i++){
if(vin[i]==pre[0]){
index=i;
}
}
root.left=reConstructBinaryTree(Arrays.copyOfRange(pre,1,index+1),Arrays.copyOfRange(vin,0,index));
root.right=reConstructBinaryTree(Arrays.copyOfRange(pre,index+1,num),Arrays.copyOfRange(vin,index+1,num));
return root;
}
}
这道题使用递归的方法来接,因为构建树可以看做构建他的左子树,构架他的右子树,然后连接上根节点,返回这个根节点,这个就是递归的式子
结束的条件是如果为空就返回null
额外需要注意的一点是java里面对于数组的操作