【问题标题】:Reaching nullptr crashes program - Binary Search Tree达到 nullptr 崩溃程序 - 二叉搜索树
【发布时间】:2021-02-15 14:36:38
【问题描述】:

我想知道当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 )时,它显然可以正常工作。 有谁知道解决方案? 谢谢

【问题讨论】:

  • 看起来你是looking for if
  • @user4581301 是的,我猜。但我就是不知道该怎么做;)如果这对我来说很容易,我不会要求的,对吧?

标签: c++ search tree binary nullptr


【解决方案1】:

当您的ss &lt;&lt; ... 语句到达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";

【讨论】:

  • 是的,效果很好。我没有那样想,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多