这是一个家庭作业。作业不是递归的,而是树结构的。我几乎完成了任务,但是我向后移动一棵树的递归方法中断了。树结构由以下类给出:
package lab12;
import java.io.Serializable;
public class Dog implements Serializable{
public Dog[] children;
public String name;
public Dog(String name)
{
this.name = name;
}
@Override
public String toString()
{
return name;
}
}
我很确定原因是返回 null;结合我的 for 循环的语句。for 循环遍历不包含任何子节点的节点,结果返回 null。这结束了该方法并将 null 传回给我的程序,这给了我空指针异常。
我无法删除 return null 语句,否则它不会编译,即使它会使用 for 循环 100% 返回。
public Dog findParent(Dog root, String name)
{
String top = "Spot";
if(top.equals(name))
{
System.out.println("No further records");
System.out.println("Goodbye.");
System.exit(0);
}
for(int i = 0; root.children != null && i < root.children.length; i++)
{
if(root.children[i].name.equals(name))
{
return root;
}
else
{
return findParent(root.children[i], name);
}
}
return null; //Compiler still requires a return here.
}
I feel like this has to be a common problem with using for loops in non-void recursive methods. Is there a way to make the compiler happy and yet not have the extra return null statement?