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

Reaching nullptr crashes program - Binary Search Tree

我想知道是否有任何方法(我认为有)可以避免在while循环到达nullptr时程序崩溃?我做了从二进制搜索树传递给字符串值的方法,但是当没有 parent 的右或左 child 时会出现问题。我的方法:

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 << ... 语句到达叶 Node* 时,其 left_child and/or 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";