Albero binario Linked

voti
-6

Sto avendo problemi a capire come ottenere la mia funzione di ricerca per lavorare per il mio albero binario restituisce vero per la radice, ma non so come fare per attraversare il resto della struttura.

public boolean contains(Object e)
     {
         return search(root, e);
     }

private boolean search(BinaryNode n, Object e)
    {

        //If the current node is null,
         //then the value clearly isn't found and return false.

         if (n == null) 
         {
             return false;
    } 
        //If the node contains the search value,
        //then the value is found and return true.
         if(n.getValue() == e)
        {
            return true;
        }


         //If the node isn't null but also doesn't contain the search value,
         //then search both the left and right subtrees

         return false;

     }
È pubblicato 27/04/2017 alle 23:22
fonte dall'utente
In altre lingue...                            


1 risposte

voti
0

Ecco un'implementazione di Contains()da qualche codice golang che avevo in giro sul mio desktop. Si porta potrebbe a Java.

// Contains indicated whether or not a value is in the tree.
func (tree *Tree) Contains(value int) bool {
    return (tree.find(tree.Root, value) != nil)
}

// find will search for a node containing a given value, in a tree whose
// root node is root.
func (tree *Tree) find(root *Node, value int) *Node {
    if nil == root {
        return nil
    }

    if value > root.Data {
        return tree.find(root.Right, value)
    } else if value < root.Data {
        return tree.find(root.Left, value)
    } // else, root.Data == node.Data

    return root
}
Risposto il 28/04/2017 a 00:05
fonte dall'utente

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