2

I have three functions to managa a binary tree :

static void insertion(Noeud* &top, Noeud *newNoeud)
{
    if(top == NULL)
        top = newNoeud;
    else if(newNoeud->nbr < top->nbr)
        insertion(top->left, newNoeud);
    else
        insertion(top->right, newNoeud);
}

static void affichage(Noeud* &top) //displaying
{
    if(top != NULL)
    {
        affichage(top->left);
        affichage(top->right);
        cout << "\n" << top->nbr;
    }
}

static Noeud* recherche(Noeud* &top, int nbr) //searching 
{
    while(top != NULL)
    {
        if(top->nbr == nbr)
            return(top);
        else if(nbr < top->nbr)
            top = top->left;
        else
            top = top->right;
    }
}

however I keep getting an error saying that I am violating the access when trying to read a memory spot. I am guessing this has to do with my pointers but I can't guess what it is.

2
  • Have you tried running in a debugger? Where exactly does it crash? Have you tried valgrind, if you're on Linux? Commented Nov 25, 2012 at 4:34
  • 1
    Since static Noeud* recherche(Noeud* &top, int nbr) means what it means in C++, you're passing top by reference, top = top->left; resp. top = top->right; will destroy your tree. Commented Nov 25, 2012 at 4:47

2 Answers 2

1

the recherche changes the top which it shouldn't.

Does this even compiled ?

static Noeud* recherche(Noeud* &top, int nbr) //searching 
{
    while(top != NULL)
    {
        if(top->nbr == nbr)
            return(top);
        else if(nbr < top->nbr)
            top = top->left;
        else
            top = top->right;
    }
}

This doesn't always return a value...

should be something like that:

static Noeud* recherche(Noeud* &top, int nbr) //searching 
{
    Noeud* it = top; //use a temporary pointer for the search.
    while(it != NULL)
    {
        if(it->nbr == nbr)
            return(it);
        else if(nbr < it->nbr)
            it = it->left;
        else
            it = it->right;
    }
    return it; //always return a value.
}
Sign up to request clarification or add additional context in comments.

Comments

1

Your search method makes your top node not point to top anymore.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.