Reputation: 544
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.
Upvotes: 2
Views: 118
Reputation: 19473
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.
}
Upvotes: 1
Reputation: 31
Your search method makes your top node not point to top
anymore.
Upvotes: 1