在二进制Serach树中插入未处理的异常抛出

时间:2018-05-25 11:01:23

标签: c++ tree binary

我有一个在二叉搜索树中插入节点的功能。我尝试插入节点时遇到崩溃。我使用VS的调试器,它告诉我抛出了未处理的异常:写入访问冲突。 m_father是nullptr。

这是我要插入的功能:

NOD *INSERT(NOD k)
{
    NOD *temp = new NOD(k);
    NOD *m_father = NULL;
    NOD *x = root;
    while (x != NULL)
    {
        m_father = x;
        if (m_father->m_key > x->m_key)
        {
            x = x->m_right_child;
        }
        x = x->m_left_child;
    }
    if (root == NULL) 
        root = temp;
    else if (temp->m_right_child->m_key > m_father->m_key)
        {
            m_father->m_right_child = temp;
        }
    m_father->m_left_child = temp;
    temp->m_father = m_father;
    return 0;
}

以下是我尝试插入节点的方法:

int temp_nod;
cin >> temp_nod;
binary_tree.INSERT(temp_nod);

2 个答案:

答案 0 :(得分:1)

else if (temp->m_right_child->m_key > m_father->m_key)

temp在这里是复制构造的(它是预期的行为吗?)。如果是从新节点创建的,则可能尚未分配m_right_child,因此您尝试取消引用nullptr
我不确定,但你想在这里查看temp密钥吗?在BST中选择正确的位置时,我没有太多理由检查子键。

另外,如评论中所述,您指定m_father-> left_child 始终,没有条件。即使在空列表中也会发生这种情况,因此我们再次尝试取消引用nullptr。我想它看起来应该更像这样:

if (root == NULL) 
    root = temp;
else if (temp->m_right_child->m_key > m_father->m_key)
{
    m_father->m_right_child = temp;
    temp->m_father = m_father;
}
else
{
    m_father->m_left_child = temp;
    temp->m_father = m_father;
}

作为旁注,如果您的函数没有返回任何有用的内容,只需将其设为void

答案 1 :(得分:0)

如果root == NULL m_father NOD *m_father = NULL;m_father->m_left_child = temp;的唯一作业将是root == NULL,则在x语句之前。

编辑:(因为如果NULL,那么while也会else if (temp->m_right_child->m_key > m_father->m_key),因此m_father->m_left_child = temp;循环不会被执行)

EDIT2:root == NULL => else if - 前者不会在if进行评估,因为{{1}}到{{1}}是真的。

相关问题