Linked Binary Tree

stemmen
-6

Ik heb probleem uitzoeken hoe om mijn zoekfunctie om te werken voor mijn binaire boom is het resultaat geldt voor de wortel, maar ik weet niet hoe om te gaan over het doorkruisen van de rest van de boom.

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;

     }
De vraag is gesteld op 27/04/2017 om 23:22
bron van user
In andere talen...                            


1 antwoorden

stemmen
0

Hier is een implementatie van Contains()van enkele golang code die ik nog had liggen op mijn bureaublad. Je kon het haven naar 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
}
antwoordde op 28/04/2017 om 00:05
bron van user

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