Reputation:
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. (default value is 0.0)
e 5
calls my find()
function and takes in the 5, 4, 8, 9.. as the key. Can anybody tell me why, even though the key's are outputted as matching, they are not returning 1?
Thanks in advance!
Upvotes: 1
Views: 393
Reputation: 178263
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
. Try
return left.find(k);
and
return right.find(k);
In addition, it appears you're returning 1
instead of a value; I only see key-related code here. You may want to return a value here instead of 1
. Also, can 0
be a valid value? If so, returning 0
may mean you found 0
or you didn't find a match. Instead of returning 0, you may want to throw a NoSuchElementException
to indicate that it's not found.
Upvotes: 5