【问题标题】:Binary Search Tree having issues with insert function二叉搜索树与插入功能有问题
【发布时间】:2017-11-11 12:05:47
【问题描述】:

我正在使用递归函数将一个节点插入到我的二叉搜索树中。如果没有根节点,该程序通过创建根节点来工作。 Root 是指向节点结构的指针。如果根已经存在,我调用工作函数。

注意: Key 是 int,Item 是 string。

在调用工作函数时,current->key(-858993460)current->item(Error reading characters of string) 不是他们预期的 values (1, "Harrold")

递归继续,直到发生此异常:

"Exception thrown: read access violation. current was 0xCCCCCCCC."

Key kItem i 是它们的期望值。这就是为什么我试图从 Node* root 访问它们的原因,它们发生了变化,我不确定为什么会发生这种情况。

感谢任何帮助

void BST::insert(Key k, Item i)
{
    if (root == nullptr) {
        root = &Node(k, i);
    }
    else insertRec(k, i, root);
}

void BST::insertRec(Key k, Item i, Node* current)
{

    if (current->key == k)//if the key of the inserted node is = to an existing key, change the item.
    {
        current->item = i;
    }
    else if (current->key > k)//if the key of the current node is larger than key inserted traverse leftchild recursively calling function
    {
        if (current->leftChild != nullptr)
            insertRec(k, i, current->leftChild);
        else
            current->leftChild = &Node(k, i);
    }
    else if (current->key < k)
    {
        if (current->rightChild != nullptr)
            insertRec(k, i, current->rightChild);
        else
            current->rightChild = &Node(k, i);
    }
}

【问题讨论】:

  • current-&gt;leftChild = &amp;Node(k, i); -- 解释这条看起来很奇怪的线的作用。存储指向临时对象的指针(注定要失败)的原因是什么?二、请发minimal reproducible example
  • 节点是一个结构。它包含 Int 键、字符串项、Node* leftChild 和 Node* rightChild。 struct BST::Node 我在这里要做的是; 1-创建一个新节点。 2-将其创建为当前节点的右或左子节点,使其具有父节点。
  • 您要做的是创建一个新节点吗?你的书和许多例子展示了如何创建新对象?你正在做的是创建一个临时的。听说过 C++ 中的new,或者更好的是std::unique_ptr&lt;&gt;make_unique?如果不是,那么在调用 insert 之前,您的整个现有 BST 都没有正确构建。
  • 嗨 Paul,问题是 leftChild 和 rightChild 没有初始化为 nullptr。所以当程序达到这个 if (current->leftChild != nullptr) 它不会操作代码。还用新的 Node(k, i) 替换 &Node(k, i) 让我可以访问 current->key。感谢您的帮助

标签: c++ binary-search-tree


【解决方案1】:

您现在在为树创建新节点时所做的是实例化一个临时的Node 对象,然后存储该对象的地址。这就是&amp;Node(k, i) 正在做的事情。

问题是临时对象将超出范围,并且您的 BST 现在包含 Node 指向不存在的东西的指针。这更有可能是您的程序因无效地址错误而停止的原因。

所以不是

&amp;Node(k,i),

使用

new Node(k, i)

这会动态分配一个新的Node,使指向这个Node 的指针“粘住”而不是临时的。

当然,当需要销毁树时,您有责任为 BST 释放内存。那时您需要遍历树节点并在每个 Node 上调用 delete

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多