1、递归的写法:
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int plow,int phigh,int [] in,int ilow,int ihigh) {
if(plow == phigh)
return new TreeNode(pre[plow]);
if(plow > phigh || ilow > phigh)
return null;
int key = pre[plow];
TreeNode root = new TreeNode(key);
//找到前序遍历中的节点在中序遍历中的位置
int i;
for(i=ilow;i<=ihigh;i++){
if(in[i] == key){
break;
}
}
int leftTreeSize = i - ilow;
root.left = reConstructBinaryTree(pre,plow+1,plow+leftTreeSize,in,ilow,i-1);
root.right = reConstructBinaryTree(pre,plow+leftTreeSize+1,phigh,in,i+1,ihigh);
return root;
}
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
return reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
}
}
有人找i值使用了HashMap来存储!
注意:终结条件!
if(plow == phigh)
return new TreeNode(pre[plow]);
if(plow > phigh || ilow > phigh)
return null;
尤其是if(plow > phigh || ilow > phigh)
条件,数组下标+1或者-1或者其他变化的时候,肯定不会在你期望的地方结束的。
public class Solution {
public int indexOfIn(int head,int[] in){
int len = in.length;
for(int i=0;i<len;i++)
if(head == in[i])
return i;
return -1;
}
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
int len = in.length;
if(len == 0)
return null;
int head = pre[0];
TreeNode root = new TreeNode(head);
int headIndex = indexOfIn(head,in);//3
int leftLen = headIndex;//3
int rightLen = len - 1 - headIndex;//4
int[] leftPre = new int[leftLen];
int[] rightPre = new int[rightLen];
for(int i=0;i<leftLen;i++){//3
leftPre[i] = pre[i+1];
}
for(int i=0;i<rightLen;i++){//4
rightPre[i] = pre[i+headIndex+1];
}
int[] leftIn = new int[leftLen];
int[] rightIn = new int[rightLen];
for(int i=0;i<leftLen;i++){
leftIn[i] = in[i];
}
for(int i=0;i<rightLen;i++){
rightIn[i] = in[i+headIndex+1];
}
root.left = reConstructBinaryTree(leftPre,leftIn);
root.right = reConstructBinaryTree(rightPre,rightIn);
return root;
}
}
这样,最后的判断就简单了,只需要判断数组的长度是不是0即可!