【发布时间】:2014-06-30 19:42:14
【问题描述】:
有人能解释一下为什么这个方法总是返回 false 吗?即使语句if(value == node.getValue()) 为真,该方法也返回假。与递归有关吗?我通过使用布尔变量来解决它,但我仍然很好奇为什么这不起作用。谢谢。
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;
}
我的解决方案(bool 是一个实例变量):
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;
}
【问题讨论】:
-
您通过“使用布尔变量”解决了这个问题?你能发布同样有效的代码吗?
-
@PM 77-1 否。它通过了
if(value == node.getValue()),但仍然返回 false。 -
啊,是的。您正在解决一个事实,即您没有返回递归调用的结果。请参阅我的(以及其他几个类似的)答案。
标签: java binary-tree