Can someone explain why this method always return false? Even though the statement if(value == node.getValue())
is true the method returns false. Something to do with recursion? I solved it by using a booelan-variable instead but I'm still curious why this doesn't work. Thanks.
public boolean contains(Node node, Integer value) {
if(node != null && node.hasValue())
if(value == node.getValue())
return true;
if(node.hasLeft())
contains(node.getLeft(), value);
if(node.hasRight())
contains(node.getRight(), value);
return false;
}
My solution(bool is an instance-variable):
public boolean contains2(Node node, Integer value) {
if(node != null && node.hasValue())
if(value == node.getValue())
bool = true;
if(node.hasLeft())
contains2(node.getLeft(), value);
if(node.hasRight())
contains2(node.getRight(), value);
return bool;
}