【问题标题】:In order traversal error?为了遍历错误?
【发布时间】:2017-05-08 09:29:14
【问题描述】:

这种递归顺序遍历方法有些麻烦 我的代码应该按顺序遍历给定的树,如果正确执行则返回 true。我通过遍历它并将元素添加到 arrayList 来做到这一点。我有一个 isSorted 方法,如果数组列表已排序(每次添加数组列表元素时都会完成),则返回 1,否则返回 0。

它的工作是返回对应于它是否已排序的 correcy 1 或 0,但之后它不会停止执行。因为如果它没有排序,那么可以肯定地说顺序遍历没有正确完成,但它说它是正确的。有人可以帮忙吗?

 public ArrayList<Integer> inOrderCheck = new ArrayList<Integer>();


boolean checkBST(Node root) {

   if(root != null){
       checkBST(root.left);
       if(addToList(root.data) == 0){
           return false;
       }

       checkBST(root.right);

   }


    return true;

   // Integer[] inOrderArray = inOrderCheck.toArray(new Integer[inOrderCheck.size()]);




}

int addToList(int data){

    //System.out.println("Initial size of inOrderCheck: " + inOrderCheck.size());
if(!(inOrderCheck.contains(data))){
   // System.out.println("Adding: " + data);
      inOrderCheck.add(data);
}

//System.out.println(" size of inOrderCheck after adddition: " + inOrderCheck.size());
   // System.out.println("Contents of inOrderCheck: " + inOrderCheck);   

  //  System.out.println("Result of isSorted: " + isSorted());   

return isSorted();    
}



int isSorted(){

int sorted = 0;        
for (int i = 1; i < inOrderCheck.size(); i++) {
     //System.out.println("Result of isSorted: " + inOrderCheck.get(i-1) + " "+ inOrderCheck.get(i));   
    if (inOrderCheck.get(i-1) < (inOrderCheck.get(i)) ) {
        sorted = 1;
    }else
        sorted = 0;
}

return sorted;
}

【问题讨论】:

  • 也许您不应该忽略从对checkBST 的递归调用返回的布尔值。
  • @Eran 喜欢什么将它们设置为布尔值?
  • @SJackson193 如果checkBST(root.left) 返回 false,您应该返回 false。 checkBST(root.right) 也一样。

标签: java algorithm binary-search-tree inorder


【解决方案1】:

您忽略了递归调用返回的值。如果对左子树或右子树的任一调用返回 false,则应返回 false。

boolean checkBST(Node root) {
    if (root != null) {
        if (!checkBST(root.left))
            return false;
        if (!addToList(root.data))
            return false;
        if (!checkBST(root.right))
            return false;
    }   
    return true;
}

此外,您的isSorted 方法存在一些问题。 首先,它应该返回布尔值。其次,当列表只包含一个元素时,它不应该返回0

我会改成:

boolean isSorted() {     
    for (int i = 1; i < inOrderCheck.size(); i++) { 
        if (inOrderCheck.get(i-1) >= inOrderCheck.get(i)) {
            return false;
        }
    }
    return true;
}

boolean addToList(int data) {
    if(!inOrderCheck.contains(data)) {
        inOrderCheck.add(data);
    } else {
        return false;
    }
    return isSorted();
}

【讨论】:

  • 我这样做了,现在添加东西时出现问题
  • 可以说它转到叶节点。它只是停在那里,永远不会回去检查根
  • @SJackson193 如果最后添加的元素导致列表未排序,则它将停止向列表添加元素,这意味着树不是 BST。
  • 它似乎只添加了最小的元素然后它就停止了
  • 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 16 18 19 20 21 22 23 24 25 26 27 28 29 30 31 像这个列表应该继续添加直到它达到 16然后意识到有重复然后返回false,我的代码只是添加了1和stios
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多