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'變量在這裏沒有用處。 –