问题描述
我想知道是否有任何方法(我认为有)可以避免while循环到达nullptr时程序崩溃?我做了从二进制搜索树传递给字符串值的方法,但是当没有右父项或左父项时,就会出现问题。我的方法:
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();
所以基本上我想知道如何告诉编译器,当它到达nullptr时,我希望它打印出一些值或字符串或其他任何内容,而不是崩溃。当我删除->数据(例如tmp-> right_child-> data)时,它可以正常工作。 有人知道解决方案吗? 谢谢
解决方法
当您的ss << ...
语句到达Node*
和/或left_child
为空的叶子right_child
时,它将尝试访问无效的data
。您不会处理这种情况,因此会导致崩溃,以及为什么删除data
访问权限才能使代码正常工作。
尝试以下方法:
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";