Znajdź węzeł, który ma kolejną wartość aktualnej wartości węzła w binarne drzewo poszukiwań

głosy
0

Mam BST z BTNode<E>„s każdy ma podwójną liczbę i mam następujące pola:

BTNode <E> root: Wskaźnik do korzenia drzewa

BTNode <E> current: Wskaźnik do bieżącego węzła

Chcę napisać metodę next (), które sprawiają, że obecne punkty do węzła, który ma kolejną wartość aktualnej wartości węzła

Oto co zrobiłem do tej pory:

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

Pomożesz mi napisać tę metodę?

Utwórz 05/05/2011 o 16:57
źródło użytkownik
W innych językach...                            


1 odpowiedzi

głosy
0

Czy sprawdzić, że indeks zwrócony przez Arrays.binarySearch () jest to, co można się spodziewać? Także elementy powinny być sortowane przed nazywając ją. I nie jest jasne, od ciebie przykład kodu jak obsłużyć przypadek, gdy wartość ta nie znajduje się w tablicy. Zakładając, że jest zawsze w tablicy czemu potem zdobycie indeksu wartość @ + 1?

Odpowiedział 05/05/2011 o 18:03
źródło użytkownik

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more