Più basso antenato comune in un binario di ricerca albero

voti
2

La sua piuttosto facile da trovare più vicino antenato comune in un BST, se tutti gli elementi sono distinti. Ma cosa succede se alcuni dei valori sono gli stessi. Fino ad ora siamo stati solo confrontando i dati di nodi e che è stato, ma ora abbiamo bisogno di richiedere l'indirizzo nodi invece di pochi valori?

È pubblicato 06/08/2011 alle 11:25
fonte dall'utente
In altre lingue...                            


3 risposte

voti
1

Sì, invece di usare solo la tua keyper il confronto, utilizzare (key, address of node)per il confronto. Questo semplifica il codice quando si tratta di chiavi non univoche.

Risposto il 06/08/2011 a 11:31
fonte dall'utente

voti
0

Senza vedere che tipo di struct che si sta utilizzando, è difficile dare dettagli, ma si potrebbe provare qualcosa di simile pseudocodice:

struct BST {
    struct BST* parent;
    struct BST* left;
    struct BST* right;
    void* value;
}

find_common_ancestor(struct BST* x, struct BST* y)
{
    set<struct BST*> ancestors;

    // Add all of x's ancestors to set.
    while (true) {
        ancestors.insert(x);

        if (x == NULL)
            break;

        x = x=>parent;
    }

    // Check y's ancestors against x's until a match is found.
    while (true) {
        if (ancestors.count(y) > 0)
            return y;

        y = y->parent;
    }
}
Risposto il 06/08/2011 a 11:41
fonte dall'utente

voti
0

qui è psudocode. semplicemente convertirli in sintassi.

GETLeastCommonAn(BINARYTREE BT, NODE A, NODE  B)
IF Root==NIL
    return NIL
ENDIF

IF Root==A OR root==B
    return Root
ENDIF

Left = GETLCA (Root.Left, A, B)
Right = GETLCA (Root.Right, A, B)

IF Left! = NIL AND Right! = NIL
    return root
ELSEIF Left! = NIL
    Return Left
ELSE
    Return Right
ENDIF
Risposto il 05/09/2014 a 07:17
fonte dall'utente

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