View Single Post
Old 02-07-2009, 16:04   #11
banryu79
Senior Member
 
L'Avatar di banryu79
 
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
Codice:
    void add(Comparable key)
    {
        BinNode newNode = new BinNode(key);
        BinNode father = null, temp = this;

        // trova il padre per il nuovo nodo
        while (temp != null)
        {
            father = temp;
            if (newNode.key.compareTo(temp.key) < 0)
                temp = temp.left;
            else
                temp = temp.right;
        }

        newNode.parent = father;

        // inserisce il nuovo nodo a destra o a sinistra del padre
        if (newNode.key.compareTo(father.key) < 0)
            father.left = newNode;
        else
            father.right = newNode;
    }
Esempio:
BinNode root = new BinNode(new Integer(8));
root.add(new Integer(4)); // lo aggiunge come figlio sinistro di root
root.add(new Integer(10)); // lo aggiunge come figlio destro di root

la classe BinNode deve accettare Comparable e quindi la chiave (key) deve essere di tipo Comparable.
__________________

As long as you are basically literate in programming, you should be able to express any logical relationship you understand.
If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it.
(Chris Crawford)
banryu79 è offline   Rispondi citando il messaggio o parte di esso