Ricerca in un legno che non è binario

voti
0

Hey ragazzi, ho creato un albero che non è un albero binario. Ora, quello che voglio è alla ricerca di un elemento. La cosa principale è il seguente: Dal momento che ho alcuna possibilità di confronto a differenza di un albero binario, devo trovare altri modi per implementare il codice. Ecco quello che ho pensato:

public TreeNode<City> search(City parent, TreeNode<City> t){
//As you guess, City class is irrelevant to the issue, I have no problem with City class.
    if (t.getCity().equals(parent)) {
        return t;
    }
    else if (t.hasLeftChild()){
        search(parent,t.getLeftChild());
    }
    else if(t.hasNextSibling()){
        search(parent,t.getNextSibling());
    }
    else//Since I know that case will never happen, the returned value is unimportant
        return t;
    }

Naturalmente, questo codice non ha funzionato. La parte difficile è che ho per restituire il valore Cerco, non appena lo trovo. Eppure, se io non riesco a trovarlo, ho ancora a restituire qualcosa. Come faccio a farlo ???

È pubblicato 25/05/2011 alle 15:03
fonte dall'utente
In altre lingue...                            


2 risposte

voti
0

Per iniziare, è necessario (in qualche modo) utilizzare il valore restituito dalle chiamate ricorsive a search()- probabilmente returnesso:

public TreeNode<City> search(City parent, TreeNode<City> t){
    if (t.getCity().equals(parent)) {
        return t;
    }
    else if (t.hasLeftChild()){
        return search(parent,t.getLeftChild());
    }
    else if(t.hasNextSibling()){
        return search(parent,t.getNextSibling());
    }
    return null;
}
Risposto il 25/05/2011 a 15:07
fonte dall'utente

voti
0

Metacode per la funzione ricorsiva che cerchi

public TreeNode<City> search(City parent, TreeNode<City> t){
    if (t.getCity().equals(parent)) {
        return t;
    }

    if (t.hasLeftChild()) {
        if (tmp = search(parent,t.getLeftChild())) {
            return tmp;            
        }
    }

    if (t.hasnextSibling()) {
        if (tmp = search(parent,t.getnextSibling())) {
            return tmp;            
        }
    }

    return false;
}
Risposto il 25/05/2011 a 15:15
fonte dall'utente

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