什么路径不返回值?

时间:2016-11-09 21:25:22

标签: c++ recursion warnings binary-search-tree

我有一个函数,可以使用递归来通过字符串键在BST中查找节点。 我收到第二个函数的警告:c4715“并非所有控制路径都返回一个值”。我无法理解究竟什么路径没有返回值..

这是我的功能:

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

1 个答案:

答案 0 :(得分:2)

这些路径

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 findNodeByKeyHelper(node->right, str);

并将else-if替换为else。例如

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