Jump to content

Search Depth

- - - - -

  • Please log in to reply
3 replies to this topic

#1
Apprentice123

Apprentice123

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 430 posts
What's wrong in my code? He does not perform the search right


Tree * searchDepth(Tree * root, element info)

{

    stack *p;

    Tree *aux;

    p = initializeStack();

    aux = root;

    pushStack(p, aux);

    while(!emptyStack(p))

    {

        if(aux->Brother != NULL)

            pushStack(p, aux->Brother);


        if(aux->info == info)

        {

            destroyStack(p);

            return aux;

        }

        if(aux->Son != NULL)

            aux = aux->Son;

        else

        {

            aux = topStack(p);

            popStack(&p);

        }

    }

    destroyStack(p);

    return NULL;

}



#2
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,717 posts
  • Programming Language:C, Java, C++, PHP, Python, Perl, Assembly, Bash, Others
  • Learning:JavaScript
You're searching the entire tree to find one element. That isn't the point of a binary tree. A usual implementation (recursively, mind you) looks like this:

Tree *searchDepth( Tree *root, element info )
{
    if( root == NULL )
        return NULL;
        
    if( info == root->info )
        return root;
    else if( info < root->info )
        return searchDepth( root->left, info );
    else
        /* info >= root->info */
        return searchDepth( root->right, info );
}
Simple, and you don't need to maintain your own stack, either. It all hinges on comparison; values less than the root's data value go in the left branch, values greater than or equal to the root's data go in the right branch. I'm not entirely sure which way your Brother and Son fields go, so you're going to have to decide that. I'm assuming this is homework--do you have to use your own stack, or are you allowed to use recursion?

BTW: I might be able to help you better if you tell me your native language (provided I can speak it).

Edited by dargueta, 22 June 2010 - 09:35 PM.
Grammar. Oh, the irony. XD

sudo rm -rf /

#3
Apprentice123

Apprentice123

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 430 posts
Not is a binary tree. And need make with this function

#4
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,717 posts
  • Programming Language:C, Java, C++, PHP, Python, Perl, Assembly, Bash, Others
  • Learning:JavaScript
Ok. So is your problem that your function never returns, it always returns NULL, or it doesn't return the right result?
sudo rm -rf /




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users