c++ - 二叉树指针错误

标签 c++ pointers recursion tree

我有三个函数来管理二叉树:

static void insertion(Noeud* &top, Noeud *newNoeud)
{
    if(top == NULL)
        top = newNoeud;
    else if(newNoeud->nbr < top->nbr)
        insertion(top->left, newNoeud);
    else
        insertion(top->right, newNoeud);
}

static void affichage(Noeud* &top) //displaying
{
    if(top != NULL)
    {
        affichage(top->left);
        affichage(top->right);
        cout << "\n" << top->nbr;
    }
}

static Noeud* recherche(Noeud* &top, int nbr) //searching 
{
    while(top != NULL)
    {
        if(top->nbr == nbr)
            return(top);
        else if(nbr < top->nbr)
            top = top->left;
        else
            top = top->right;
    }
}

但是,我不断收到错误消息,指出我在尝试读取内存点时违反了访问权限。我猜这与我的指针有关,但我无法猜出它是什么。

最佳答案

recherche 更改了它不应该更改的 top

这甚至可以编译吗?

static Noeud* recherche(Noeud* &top, int nbr) //searching 
{
    while(top != NULL)
    {
        if(top->nbr == nbr)
            return(top);
        else if(nbr < top->nbr)
            top = top->left;
        else
            top = top->right;
    }
}

这并不总是返回一个值...

应该是这样的:

static Noeud* recherche(Noeud* &top, int nbr) //searching 
{
    Noeud* it = top; //use a temporary pointer for the search.
    while(it != NULL)
    {
        if(it->nbr == nbr)
            return(it);
        else if(nbr < it->nbr)
            it = it->left;
        else
            it = it->right;
    }
    return it; //always return a value.
}

关于c++ - 二叉树指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13548283/

相关文章:

c++ - 处理 RAII 成员变量的正确方法是什么?

php - MySQL、PHP 和 PDO 中的高效后代记录删除

c++ - C 和 C++ : Partial initialization of automatic structure

function - 无效的二进制操作数,缺少理论

c++ - Brace-init-list 和赋值

c - 数组元素乘法的二叉树方法

java - 如何在此函数中正确使用递归?

algorithm - QuickSort 程序达到最大递归限制 500?

c++ - 继承加法赋值操作,如何返回正确的类型?

c++ - 自从移动到 64 位后,我在随机 glVertexAttribArray 调用中从 nvoglv64.dll 获得了访问冲突