我正在尝试从PreOrder和inorder构造BST
// Construct Binary Tree From Inorder And Preorder
public class Solution {
public TreeNode buildTree(ArrayList<Integer> A, ArrayList<Integer> B) {
return buildTreeUtil(A,0,A.size()-1,B,0,B.size()-1);
}
public TreeNode buildTreeUtil(ArrayList<Integer> inOrder,int inOrderStart,int inOrderStop,
ArrayList<Integer> preOrder,int preOrderStart,int preOrderStop){
if(inOrderStart > inOrderStop || preOrderStart>preOrderStop){
return null;
}
TreeNode root = new TreeNode(preOrder.get(preOrderStart));
int index = 0;
for(int i=0;i<inOrder.size()-1;i++){
if(inOrder.get(i)==preOrder.get(preOrderStart)){
index = i;
break;
}
}
root.left = buildTreeUtil(inOrder,inOrderStart,index-1,
preOrder,preOrderStart+1,preOrderStart+(index-inOrderStart));
root.right = buildTreeUtil(inOrder,index+1,inOrderStop,
preOrder,preOrderStart+index-inOrderStart+1,preOrderStop);
return root;
}
}
正在给予例外
索引超出范围
答案 0 :(得分:0)
与IndexOutOfBoundsException无关,但是以下代码行不正确地使用相等运算符==来比较两个Integer实例,而应使用.equals()方法:
错误代码:
if(inOrder.get(i)==preOrder.get(preOrderStart)){
正确的代码:
if(inOrder.get(i).equals(preOrder.get(preOrderStart))) {
可能发生IndexOutOfBoundsException,因为以下代码行未针对preOrderStart和preOrderStop参数值(小于或等于ArrayList的size()-1)进行保护:
root.left = buildTreeUtil(inOrder,inOrderStart,index-1,
preOrder,preOrderStart+1,preOrderStart+(index-inOrderStart));
root.right = buildTreeUtil(inOrder,index+1,inOrderStop,
preOrder,preOrderStart+index-inOrderStart+1,preOrderStop);
考虑一下,如果变量索引的值为0,则上面的代码中会发生什么。参数index-1的值为-1。