I'm having trouble adding ("books") nodes to a tree. I have a class (BookRecord) that has a pointer to BookRecord *left and BookRecord *right, they are private but each have a get and set function..get/set left/right()
I am trying to accomplish:
- Add a single node that is passed in (br) to the tree, ordered by its key, a stock number.
- Return TRUE after it works.
Now, the part I am confused about is, how to add a node to the tree. I can print out the info on the nodes that are being passed in with no problem, so they are actually being passed in correctly.
But, when I try temp->setLeft(temp); or temp->setRight(temp) the program crashes, which could be caused by trying to access a NULL pointer.
How would I add a node to this tree??
I can post more code or information if this is too vague but any suggestions would help!
(Also, no, I cant use the STL. This is an exercise in trees so we MUST write it out without using the STL or vectors.)
bool Book_Database::addBook(BookRecord *br)
{
BookRecord *temp;
BookRecord *back;
temp = root;
back = NULL;
if(temp != NULL)
cout << "Current stock number = " << temp->getStockNum() << "\n";
while(temp != NULL) // Loop till temp falls out of the tree
{
back = temp;
//********************# 3 gets stuck here*****************
if(br->getStockNum() < temp->getStockNum()){
temp = temp->getLeft();
}
else {
temp = temp->getRight();
}
if(temp != NULL)
cout << "Current stock number = " << temp->getStockNum() <<"\n";
else
cout << "Temp is now NULL.\n";
}
// Now attach the new node to the node that back points to
if(back == NULL) // Attach as root node in a new tree
root = br;
else
{
if(br->getStockNum() < back->getStockNum())
back->setLeft(br);
else
back->setRight(br);
}
return(true);
}