【问题标题】:java- BST recursive find a valuejava-BST递归查找值
【发布时间】:2014-06-30 06:57:14
【问题描述】:

我有一棵 BST 树。我想创建一个方法来获取一个值并返回包含它的值的节点的级别(root = 0),没有这样的节点吗?返回-1。 我想递归地做。 这段代码工作得很好:

    private int recursiveContains(BinaryNode node, int searchVal){
    int nodeKey = node.nodeKey;
    if (searchVal < nodeKey){
        if (node.leftChild != EMPTY_NODE)
            return 1 + recursiveContains(node.leftChild, searchVal);
    }else if (searchVal > nodeKey){
        if (node.rightChild != EMPTY_NODE)
            return 1 + recursiveContains(node.rightChild, searchVal);
    }
    return 0;
}

但是,只要树包含搜索值。

当我到达叶子但没有找到值时,如何停止迭代并返回 -1? 可以递归吗?

谢谢

【问题讨论】:

    标签: java recursion binary-search-tree


    【解决方案1】:

    您只需要调整您的最终案例。现在,如果该值不在树中,您只需返回将插入该值的节点的深度,因为您的最终情况只是return 0。相反,您需要明确检查当前节点是否确实是正确的节点。如果是,可以返回0;否则你应该返回-1。然后,递归调用需要查找该特殊值并适当地处理它。

    我可能会把这个明确的检查——这是请求节点的基本情况——放在开头。最后,您的“失败”值(如果没有其他条件为真,则返回)是-1。所以你最终会得到这样的结果:

    // WARNING: UNTESTED CODE
    if (searchVal == nodeKey) {
        return 0;
    } else if (searchVal < nodeKey && node.leftChild != EMPTY_NODE) {
        int childResult = recursiveContains(node.leftChild, searchVal);
        if (childResult != -1) { // Only use the child result if the value was found.
            return 1 + childResult;
        }
    } else if (searchVal > nodeKey && node.rightChild != EMPTY_NODE) {
        int childResult = recursiveContains(node.rightChild, searchVal);
        if (childResult != -1) { // Only use the child result if the value was found.
            return 1 + childResult;
        }
    }
    // If you haven't returned by now, the value can't be found along this path.
    return -1;
    

    【讨论】:

    • 仍然无法正常工作。如果未找到节点,则返回最近节点 1 的高度
    • @user3150902 正如我在第一段末尾传递的那样,您仍然需要考虑递归调用中可能的 -1 值并适当地处理它们。我已经编辑了一些示例代码来说明我的意思:如果递归调用返回 -1,你不应该返回它:只要让它落到“未找到”的值。
    猜你喜欢
    • 2013-11-26
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    相关资源
    最近更新 更多