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