Finding the smallest element in a Binary Search Tree - entering infinite loop
I am using recursive method to create a Binary Search Tree. My objective is to find the lowest element in the tree. Below is my code.
Insertion
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<<"S开发者_运维百科ome error has occurred.Time to debug!"<<std::endl;
return root;
}
MinValue Function
int minValue(node curPtr)
{
node temp = curPtr;
while ( curPtr )
{
temp = curPtr->lChild;
}
return (temp->info);
}
The reason why ( IMO ) my minValue() is entering into infinite loop is due to curPtr is always not NULL. How can i make it NULL after i have inserted the data using insert() function.
EDIT: Found the bug..so stupid of me. Thanks to Raymond
below is the edited minValue()
int minValue(node curPtr)
{
node temp = curPtr;
while ( temp->lChild )
{
temp = temp->lChild;
}
return (temp->info);
}
Thanks Kelly.
You never modify curPtr in your loop.
精彩评论