Linked Binary Tree

stimmen
-6

Ich habe Probleme, herauszufinden, wie meine Suchfunktion bekommen für meinen binären Baum zu arbeiten gibt es für die Root wahr, aber ich weiß nicht, wie sie durchqueren den Rest des Baumes zu gehen.

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;

     }
Veröffentlicht am 27/04/2017 um 23:22
quelle vom benutzer
In anderen Sprachen...                            


1 antworten

stimmen
0

Hier ist eine Implementierung der Contains()von einigen golang Code , den ich hatte auf meinem Schreibtisch herumliegen. Sie könnten Portierung auf 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
}
Beantwortet am 28/04/2017 um 00:05
quelle vom benutzer

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