什么路径没有return值?

What path doesn't return the value?

我有一个函数可以通过递归的字符串键在 BST 中找到节点。 我收到第二个函数的警告:c4715 "not all control paths return a value"。我不明白什么路径没有 return 值..

这是我的函数:

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);
        }
    }
}

这些路径

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 没有。

您应该插入 return 关键字。例如

        return findNodeByKeyHelper(node->right, str);

并将最后的 else-if 替换为 else。例如

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