Linked binar copac

voturi
-6

Sunt care au o problema imaginind cum să obțineți funcția de căutare pentru a lucra pentru copacul meu binar returnează adevărat pentru rădăcină, dar eu nu știu cum să meargă despre traversării restul arborelui.

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;

     }
Întrebat 27/04/2017 la 23:22
sursa de către utilizator
În alte limbi...                            


1 răspunsuri

voturi
0

Aici este o implementare de Contains()la unele cod golang am avut situată în jurul valorii de pe desktop - ul meu. Ai putea port pentru 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
}
Publicat 28/04/2017 la 00:05
sursa de către utilizator

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