【问题标题】:Binary tree pointer error二叉树指针错误
【发布时间】:2012-11-25 04:27:52
【问题描述】:

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

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;
    }
}

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

【问题讨论】:

  • 你试过在调试器中运行吗?它究竟在哪里崩溃?如果您使用的是 Linux,您是否尝试过 valgrind?
  • 因为 static Noeud* recherche(Noeud* &amp;top, int nbr) 表示它在 C++ 中的含义,所以您将通过引用传递 toptop = top-&gt;left; resp。 top = top-&gt;right; 会毁掉你的树。

标签: c++ pointers recursion tree


【解决方案1】:

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.
}

【讨论】:

    【解决方案2】:

    您的搜索方法使您的顶部节点不再指向top

    【讨论】:

      猜你喜欢
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多