在二进制搜索树中查找具有当前节点值的下一个值的节点

时间:2011-05-05 15:57:55

标签: java binary-search-tree

我有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());
        }
    }

你能帮我写一下这个方法吗?

1 个答案:

答案 0 :(得分:0)

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