How to save "flag" when i set it. For exemple, when i am in block
if (hashFunction(value) == hashFunction(node.value))
{
flag = true;
return flag;
}
in debug flag = true, but next step and pointer is in
if (hashFunction(value) < hashFunction(node.value))
{
if (node.left != null)
{
findPrivate(value, node.left);------THERE
} else
{
flag = false;
return flag;
}
}
And in result, my method return false. How to fix it? Sorry for my english. Full code is bellow.
private boolean findPrivate(T value, Node node)
{
if (node == null)
{
flag = false;
return flag;
}
if (hashFunction(value) == hashFunction(node.value))
{
flag = true;
return flag;
}
if (hashFunction(value) > hashFunction(node.value))
{
if (node.rigth != null)
{
findPrivate(value, node.rigth);
} else
{
flag = false;
System.out.println("value= " + value + " " + flag);
return flag;
}
}
if (hashFunction(value) < hashFunction(node.value))
{
if (node.left != null)
{
findPrivate(value, node.left);
} else
{
flag = false;
return flag;
}
}
return flag;
}
The problem is that when you recurse, you're ignoring the return value:
findPrivate(value, node.left);
I haven't looked in detail, but you may well just be able to change each occurrence of that to:
return findPrivate(value, node.left);
I would also suggest removing your flag
variable completely - it's not clear where it's declared anyway, but it looks like it should probably not be used; instead, just return the value directly. For example:
if (node.left != null)
{
return findPrivate(value, node.left);
} else
{
return false;
}
... which can then be easily refactored to:
return node.left != null ? findPrivate(value, node.left) : false;
And in fact, as you already return false
if node
is null, you can just use:
return findPrivate(value, node.left);
in that case. I suspect you can refactor your code pretty simply along those lines...
You need to return the value from the recursive call:
private static final class Node<T> {
protected T value;
protected Node<T> right;
protected Node<T> left;
private boolean findPrivate(T value, Node<T> node) {
if (node == null) {
return false;
}
if (hashFunction(value) == hashFunction(node.value)) {
return true;
}
if (hashFunction(value) > hashFunction(node.value)) {
if (node.right != null) {
return findPrivate(value, node.right);
} else {
return false;
}
}
if (hashFunction(value) < hashFunction(node.value)) {
if (node.left != null) {
return findPrivate(value, node.left);
} else {
return false;
}
}
throw new UnsupportedOperationException("cannot compare hashCodes");
}
private int hashFunction(T value) {
//stuff
}
}
You do not need to actually save a flag
, you just need to return
the value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.