我正在尝试在二叉树中实现find方法.当方法需要返回一个值时会出现问题,但即使在同一个分号中执行其他行时,它似乎也没有执行该语句.
public String find(Node currentNode, String value)
{
if(isEmpty())
{
return null;
}
else
{
if(currentNode.getData().compareToIgnoreCase(value) == 0)
{
System.out.println("current -> "+currentNode.getData()); //showing
return currentNode.getData(); //not executing
}
if(value.compareToIgnoreCase(currentNode.getData()) < 0)
{
find(currentNode.getLeft(), value);
}
else if(value.compareToIgnoreCase(currentNode.getData()) > 0)
{
find(currentNode.getRight(), value);
}
}
return null; //always executing
}
Run Code Online (Sandbox Code Playgroud)
我期待"a"但返回null.
执行该行时
find(currentNode.getLeft(), value);
Run Code Online (Sandbox Code Playgroud)
您的语句return currentNode.getData();正在执行,但您忽略了您的递归调用返回的内容.(类似于getRight()语句.)然后if/else语句完成,return null底部执行.这就是你总是得到的原因null.
返回递归调用返回的任何内容,以便返回的值正确传播回原始调用,例如:
return find(currentNode.getLeft(), value);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |