0
我使用递归方法创建二叉搜索树。我的目标是找到树中最低的元素。以下是我的代码。查找二叉搜索树中的最小元素 - 输入无限循环
插入
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)我minValue(最小值)()正在进入无限循环的原因是由于curPtr始终不为空。如何在使用insert()函数插入数据后使其成为NULL。
编辑:发现了错误..我愚蠢的。下面感谢Raymond
是所编辑的minValue(最小值)()
int minValue(node curPtr)
{
node temp = curPtr;
while (temp->lChild)
{
temp = temp->lChild;
}
return (temp->info);
}
感谢 凯利。
请注意,由于您在'minValue'函数中按值传递了'curPtr',它已经被复制:'temp'变量在这里没有用处。 –