二进制搜索树有插入功能的问题

时间:2017-11-11 12:05:48

标签: c++ binary-search-tree

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

注意: Key为int,Item为字符串。

调用辅助功能时,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);
    }
}

1 个答案:

答案 0 :(得分:0)

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

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

所以而不是

&Node(k,i)

使用

new Node(k, i)

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

当然,当你需要销毁树时,你负责为BST释放内存。那时您需要浏览树节点并在每个delete上调用Node

相关问题