【问题标题】:I am not gettin how to get rid of error here我没有得到如何摆脱这里的错误
【发布时间】:2018-09-13 13:32:31
【问题描述】:
#include <iostream>

using namespace std;

class Node {
public:
    int data;
    Node *left, *right;
    Node()
    {
        data = NULL;
        left = right = NULL;
    }
};

Node* insertBST(Node* root, int value)
{
    if (root == NULL) {
        root->data = value;
        root->left = root->right = NULL;
    }
    if ((root->data) > value)
        insertBST(root->left, value);
    if ((root->data) < value)
        insertBST(root->right, value);
}

Node* printBST(Node* root)
{
    if (root != NULL) {
        printBST(root->left);
        cout << "\n" << root->data;
        printBST(root->right);
    }
}

int main()
{
    Node* root = new Node;
    insertBST(root, 30);
    insertBST(root, 20);
    insertBST(root, 40);
    insertBST(root, 70);
    insertBST(root, 60);
    insertBST(root, 80);
    printBST(root);
}

以上是我为实现二叉搜索树而编写的代码。当我执行它时,程序停止响应并关闭。我尝试从 pythontutor.com 获得帮助,但我无法解决它。我应该怎么做才能让它正常运行? 这里是它停止的地方:Click to see

感谢任何帮助,我是编写程序的新手。

【问题讨论】:

  • 我们需要处理一个错误。如果您在调试器中运行它,您应该会收到一条实际的错误消息。
  • 我无法解决错误。
  • insertBST 从不分配新节点。第二次插入应该给你一个段错误。
  • @meowgoesthedog 是的,第二次插入出现错误。如何处理?
  • 阅读 BST 插入并重试。看来你还没有完全理解。

标签: c++ data-structures


【解决方案1】:

insertBST 中,在root == NULL 的情况下,您不会创建新节点并尝试修改root 的内容,因为这是null,它应该会导致访问冲突或分段错误。

我认为您的程序挂起而不是崩溃的原因是您使用的在线编译器会忽略无效写入,而是允许程序继续运行。这可能会通过insertBST 函数以无限递归结束。

要解决此问题,您需要分配一个新节点,一种方法如下:

void insertBST(Node*& root, int value)
{
    if (root == NULL) {
        root = new Node();
        root->data = value;
        root->left = root->right = NULL;
    }
    if ((root->data) > value)
        insertBST(root->left, value);
    if ((root->data) < value)
        insertBST(root->right, value);
}

请注意,您的程序会泄漏它分配的所有节点。您应该在Node 中编写一个析构函数,删除所有子节点并在程序结束时调用delete root。或者根本不使用原始指针,而是使用std::shared_ptrstd::unique_ptr

【讨论】:

  • @new_Coder 如果它解决了您的问题,请考虑接受这个答案。
  • 我无法正确打印 BST。输出为:0 30 20 40 70 60 80。但预期输出为:30 20 40 70 60 80
  • @new_Coder 你的问题是如何让你的代码运行没有错误。没有提及预期的行为/输出。
  • 当我运行代码时,我会按顺序得到数字,这就是我期望的输出
猜你喜欢
  • 1970-01-01
  • 2020-03-25
  • 1970-01-01
  • 2015-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 2017-04-04
相关资源
最近更新 更多