I wonder if there is any way (I think there is) to avoid program crash when while loop is reaching nullptr? I did method that passes to string values from Binary Search Tree, but the problem occures when there is no right or left child of parent. My method:
string to_string()
{
stringstream ss;
Node<T>* tmp = root;
queue<Node<T>*> q;
while (!q.empty() || tmp != NULL)
{
if (tmp != NULL)
{
q.push(tmp);
tmp = tmp->left_child;
}
else
{
tmp = q.front();
q.pop();
ss << "Data: " << tmp->data << " Left child: " << tmp->left_child->data << " Right child: " << tmp->right_child->data << " \n";
tmp = tmp->right_child;
}
}
return ss.str();
So basically I want to know how tell compiler that when it reaches nullptr I want it to print out some value or string or whatever instead of crashing. When I remove ->data (tmp->right_child->data for example) it works fine, obviously. Does anyone know the solution? thanks
When your ss << ...
statement reaches a leaf Node*
whose left_child
and/or right_child
are null, it tries to access data
that is invalid. You are not handling that condition, hence the crash, and why removing the data
access makes the code work.
Try this instead:
ss << "Data: " << tmp->data;
if (tmp->left_child != NULL) // <-- add this
ss << " Left child: " << tmp->left_child->data;
if (tmp->right_child != NULL) // <-- add this
ss << " Right child: " << tmp->right_child->data;
ss << " \n";