达到nullptr使程序崩溃-二进制搜索树



我想知道当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时,我希望它打印出一些值或字符串或其他什么,而不是崩溃。当我删除->data(例如tmp->right_child->data(,它显然运行良好。有人知道解决办法吗?感谢

ss << ...语句到达left_child和/或right_child为null的叶Node*时,它会尝试访问无效的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";

最新更新