问题
i made two functions, one to find and return smallest key in a red - black tree and the other one returns a pointer to a particular node with that node's key as input.These functions work fine with all nodes except the nodes with the highest key and the lowest key.The program stops working and gives the C4716 warning . the keys are int array[] = { 50, 26, 45, 34, 23, 78, 84, 93, 14, 16, 100, 57, 62};
int Tree::findsmallest()
{
return findsmallestprivate(root);
}
int Tree::findsmallestprivate(node* ptr)
{
if (root != NULL)
{
if (ptr->left != NULL)
{
findsmallestprivate(ptr->left);
}
else
{
return ptr->key;
}
}
else
{
cout << "There was no tree" << endl;
return -1;
}
}
Tree::node* Tree::returnnode(int key)
{
return returnnodepri(key, root);
}
Tree::node* Tree::returnnodepri(int key, node* ptr)
{
if (ptr->key == key)
{
return ptr;
}
else if (ptr->key < key)
{
returnnodepri(key, ptr->right);
}
else if (ptr->key > key)
{
returnnodepri(key, ptr->left);
}
else
{
return NULL;
}
}
回答1:
In if (ptr->left != NULL)
you fail to return a value, as the compiler says. You need to return a value.
回答2:
In findsmallestprivate
:
If condition ptr->left != NULL
holds, you do not return anything. You just run findsmallestprivate(ptr->left);
and then exit, but don't return expected int
.
warning C4715: not all control paths return a value
means that you have a function which may not return a value sometimes depending of its input.
Your other problems are the same as with findsmallestprivate
.
In returnnodepri
:
In case of ptr->key < key
or ptr->key > key
you don't return expected Tree::node*
. You run returnnodepri
, but not return any value as a result.
来源:https://stackoverflow.com/questions/26314846/warning-c4715-not-all-control-paths-return-a-value-c