kekyc kekyc - 28 days ago 12
C++ Question

What path doesn't return the value?

I have a function to find the node in BST by its string key, using recursion.
I'm getting the warning for second function : c4715 "not all control paths return a value". I can't understand what exactly path doesn't return the value..

Here's my functions:

TreeNode* Tree::findNodeByKey(const string &str) {
if (root == NULL) {
cout << "Tree is empty, nothing found" << endl;
return nullptr;
}

else {
return findNodeByKeyHelper(root, str);
}
}

TreeNode* Tree::findNodeByKeyHelper(TreeNode *node, const string &str) {
if (node->data == str) {
cout << "node is found" << endl;
return node;
}
else if (str < node->data) {
if (node->left == nullptr) {
cout << "element was not found" << endl;
return nullptr;
}
else {
findNodeByKeyHelper(node->left, str);
}
}
else if (str > node->data) {
if (node->right == nullptr) {
cout << "element was not found" << endl;
return nullptr;
}
else {
findNodeByKeyHelper(node->right, str);
}
}
}

Answer

These paths

else if (str < node->data) {
    if (node->left == nullptr) {
        cout << "element was not found" << endl;
        return nullptr;
    }
    else {
        findNodeByKeyHelper(node->left, str);
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    }
}
 else if (str > node->data) {
    if (node->right == nullptr) {
        cout << "element was not found" << endl;
        return nullptr;
    }
    else {
        findNodeByKeyHelper(node->right, str);
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    }
}

return nothing.

You should insert the return keyword. For example

        return findNodeByKeyHelper(node->right, str);

And substitute the last else-if for else. For example

if (node->data == str) {
    //...
}
 else if (str < node->data) {
    //...
}
 else  {
 ^^^^^^^
    //...
}