这道题要用到递归是肯定的,但是如果掌握的库函数够多还是可以简化代码的。
首先讲一下最简单的,不知道数组的copy函数的情况下,最简单的做法:
多写一个函数,肯定是必要的。
主要注意要控制好下标的计算,不然很容易出错。
/**
* 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) {
return constructNode(pre,in,0,pre.length,0,in.length);
}
TreeNode constructNode(int []pre,int []in,int startPre,int endPre,int startIn,int endIn){
if(startPre == endPre){
return null;
}
TreeNode treeNode = new TreeNode(pre[startPre]);
int parentIndex = startPre;
for(int i = startIn;i < endIn;i++){
if(in[i] == pre[startPre]){
parentIndex = i;
break;
}
}
treeNode.left = constructNode(pre,in,startPre+1,startPre+1+parentIndex-startIn,
startIn,parentIndex);
treeNode.right = constructNode(pre,in,startPre+parentIndex-startIn+1,endPre,parentIndex + 1,endIn);
return treeNode;
}
}
最简单做法,使用库函数copy。
/**
* 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 [] in) {
if(pre.length != in.length || 0 == pre.length){
return null;
}
TreeNode treeNode = new TreeNode(pre[0]);
for(int i = 0;i < in.length;i++){
if(pre[0] == in[i]){
treeNode.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,1 + i),Arrays.copyOfRange(in,0,i));
treeNode.right = reConstructBinaryTree(Arrays.copyOfRange(pre,1+i,pre.length),Arrays.copyOfRange(in,i+1,in.length));
}
}
return treeNode;
}
}