查找二进制搜索树中的最小元素 - 进入无限循环

时间:2011-09-03 15:09:21

标签: c++ binary-search-tree

我正在使用递归方法来创建二叉搜索树。我的目标是找到树中的最低元素。以下是我的代码。

插入

node insert(node root, int value)
{
        if ( root == NULL )
        {
                return ((newNode(value)));
        }

        if ( root->info == value )
        {
                std::cout<<"Duplicate entry found!"<<std::endl;
                return root;
        }
        else if ( root->info > value )
        {
                root->lChild = insert(root->lChild,value);
        }
        else if ( root->info < value )
        {
                root->rChild = insert(root->rChild,value);
        }
        else 
                std::cout<<"Some error has occurred.Time to debug!"<<std::endl;

        return root;
}

MinValue函数

int minValue(node curPtr)
{
        node temp = curPtr;
        while ( curPtr )
        {
                temp = curPtr->lChild;
        }
        return (temp->info);
}

(IMO)myValue()进入无限循环的原因是由于curPtr始终不为NULL。在使用insert()函数插入数据后,如何使其为NULL。

编辑:发现了这个错误......对我来说太愚蠢了。感谢Raymond

下面是编辑的minValue()

int  minValue(node curPtr)
{
  node temp = curPtr;
  while ( temp->lChild )
  {
     temp = temp->lChild;
  }
  return (temp->info);
}

由于 凯利。

1 个答案:

答案 0 :(得分:10)

您永远不会在循环中修改curPtr。

相关问题