简体   繁体   English

具有键值对的树找不到键

[英]Tree With Key-Value Pair Not Finding Key

I have a Tree that stores key's and their values. 我有一棵树,存储键及其值。 Here is my find operation: 这是我的查找操作:

public int find(int k) {
    System.out.println(k + " : " + this.k);
    if (k == this.k) {
        return 1;
    }

    if (k < this.k){
        if (left != null) {
            left.find(k);
        }
    } else {
        if (right != null) {
            right.find(k);
        }
    }
    return 0;
}

This works fine when attempting to find the root of the tree. 尝试找到树的根时,此方法工作正常。 For example, here is some output of inputting and finding keys: 例如,这是输入和查找键的一些输出:

在此处输入图片说明

c 5 generates a root node with a single key. c 5使用单个密钥生成根节点。 (default value is 0.0) (默认值为0.0)

e 5 calls my find() function and takes in the 5, 4, 8, 9.. as the key. e 5调用我的find()函数,并以5、4、8、9 ..作为键。 Can anybody tell me why, even though the key's are outputted as matching, they are not returning 1? 谁能告诉我为什么即使键的输出是匹配的,但它们却不返回1?

Thanks in advance! 提前致谢!

If you don't find the key in the root, you are calling your method recursively on the left or right child, but you're ignoring the result and returning 0 . 如果在根目录中找不到该键,则将在左侧或右侧子级上递归调用方法,但是您将忽略结果并返回0 Try 尝试

return left.find(k);

and

return right.find(k);

In addition, it appears you're returning 1 instead of a value; 另外,您似乎返回的是1而不是值。 I only see key-related code here. 我在这里只看到与密钥相关的代码。 You may want to return a value here instead of 1 . 您可能要在这里返回一个值,而不是1 Also, can 0 be a valid value? 另外, 0可以是有效值吗? If so, returning 0 may mean you found 0 or you didn't find a match. 如果是这样,则返回0可能意味着您找到了0或没有找到匹配项。 Instead of returning 0, you may want to throw a NoSuchElementException to indicate that it's not found. 您可能要抛出NoSuchElementException ,而不是返回0,而不是返回0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM