【问题标题】:Find the node that has next value of current node value in Binary Search Tree在二叉搜索树中找到具有当前节点值下一个值的节点
【发布时间】:2014-04-10 05:41:08
【问题描述】:

我有BTNode<E> 的 BST,每个都有双数,我有以下字段:

BTNode <E> root: 指向树根的指针

BTNode <E> current:指向当前节点的指针

我想写一个方法 Next() 使当前点指向具有当前节点值的下一个值的节点

这是我到目前为止所做的:

public boolean Next()
    {
        // List<E> tempList = new ArrayList<E>();     // Creating new list (I defined this at the begining of the class)
        E tempValue = current.getElement();           // Gets the value of current element
        makeSortedList(root);               //
        E[] tempArray = (E[]) tempList.toArray();           // Convert the list to an array
        int index = Arrays.binarySearch(tempArray, tempValue);  // Find the position of current node value in the array
        if(index >= count) // count is no. of nodes in the tree
        {
             E targetValue = tempArray[index + 1];         // Store the target value in a temporary variable
             search(targetValue);                          // This method searches for the node that has targetValue and make that node as the current node
             return true;
        }
        else return false;
    }

    // This method takes the values of the tree and puts them in sorted list
    private void makeSortedList(BTNode<E> myNode)
    {
        if(myNode != null)
        {
            makeSortedList(myNode.getLeft());
            tempList.add(myNode.getElement());
            makeSortedList(myNode.getRight());
        }
    }

你能帮我写这个方法吗?

【问题讨论】:

  • 您的 makeSortedList 根本不进行排序。
  • 我尝试使用中序遍历将其排序为“树排序技术”
  • 不兼容的类型 - 找到 java.lang.Object[] 但预期为 E[]
  • 最简单的尝试是有一个基本的演员表 - (E[])tempList.toArray()。这可能会给你你需要的东西。或者,使用.toArray(new E[0]) 方法。
  • 好的解决了这个问题。现在我有一个错误 int index = Collections.binarySearch(tempArray, tempValue);

标签: java binary-search-tree


【解决方案1】:

您是否检查过 Arrays.binarySearch() 返回的索引是否符合您的预期? 此外,在调用之前应该对元素进行排序。并且从您的代码示例中不清楚当在数组中找不到值时如何处理这种情况。假设它总是在数组中,为什么还要检索值@index+1?

【讨论】:

  • 我编辑了代码,以便当值不在数组中时处理
  • 顺便说一句,当我检查代码时,当前代码仍然相同并且没有改变,也许 makeSortedList() 并没有真正创建排序列表?
猜你喜欢
  • 2015-08-24
  • 1970-01-01
  • 2014-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多