Java 递归地查找元素
我有一个看起来像树的数据结构:Java 递归地查找元素,java,recursion,Java,Recursion,我有一个看起来像树的数据结构: A -> A -> A -> A -> A -> A -> A -> A -> A 基本上,A可以由另一个A或多个A组成 我想找到一个带有ID的特定a public A findParticularA(int id) { if(this.getID == id) { return this; } else
A -> A
-> A
-> A -> A -> A
-> A
-> A
-> A
基本上,A
可以由另一个A
或多个A
组成
我想找到一个带有ID的特定a
public A findParticularA(int id)
{
if(this.getID == id)
{
return this;
}
else
findAHelper(this, id);
}
public A findAHelper(A root, int id)
{
for(A a : root.getChildren())
{
if(a.getID == id)
return a;
else
findAHelper(a, id);
}
return null;
}
这仅在我要查找的A
正好位于第一个根A
之后时有效
A -> A
-> **A** will be found
但是如果我想要一个
A
在树中更深一点,那么它就不起作用了。这是因为我没有正确返回。请帮助。您需要在findParticularA
中返回findAHelper的请求
在findAHelper
中,循环使您深入树的三个分支;希望A会从这些分支中恢复,但不会从所有分支中恢复,只有一个分支。其余的(或全部)将返回null
因此,您需要捕获findAHelper的返回值,查看它是否为null,以决定是否返回它-如果它是A(非null),则返回它,否则不返回,并让循环沿着下一个树分支继续
我不能马上用Java正确地编写它,但我建议的改变是:
public A findParticularA(int id)
{
if (this.getID == id)
{
return this;
}
else
{
return findAHelper(this, id); # here
}
}
public A findAHelper(A root, int id)
{
for(A a : root.getChildren())
{
if(a.getID == id)
{
return a;
}
else
{
tmp = findAHelper(a, id); # here
if (tmp is not null) { #
return tmp #
}
}
}
return null;
}
您需要在
findParticularA
中返回FindHelper的reult
在findAHelper
中,循环使您深入树的三个分支;希望A会从这些分支中恢复,但不会从所有分支中恢复,只有一个分支。其余的(或全部)将返回null
因此,您需要捕获findAHelper的返回值,查看它是否为null,以决定是否返回它-如果它是A(非null),则返回它,否则不返回,并让循环沿着下一个树分支继续
我不能马上用Java正确地编写它,但我建议的改变是:
public A findParticularA(int id)
{
if (this.getID == id)
{
return this;
}
else
{
return findAHelper(this, id); # here
}
}
public A findAHelper(A root, int id)
{
for(A a : root.getChildren())
{
if(a.getID == id)
{
return a;
}
else
{
tmp = findAHelper(a, id); # here
if (tmp is not null) { #
return tmp #
}
}
}
return null;
}
你可以用一种方法来做这件事。您不需要
findparticular
public A findA (A root, int id)
{
if (root.getID == id)
return root;
A[] children = root.getChildren();
A res = null;
for (int i = 0; res == null && i < children.length; i++)
{
res = findA(children[i], id);
}
return res;
}
你可以用一种方法来做这件事。您不需要
findparticular
public A findA (A root, int id)
{
if (root.getID == id)
return root;
A[] children = root.getChildren();
A res = null;
for (int i = 0; res == null && i < children.length; i++)
{
res = findA(children[i], id);
}
return res;
}
事实并非如此。我以前试过。你确定
root.getChildren()
的行为符合预期吗?findAHelper(这个,id)
应该类似于a=findAHelper(这个,id);如果(a!=null){returna;}
“这只在”否“时起作用,它不起作用,因为该代码不会编译,所以永远不会起作用。不,什么时候,什么时候,什么时候,什么时候。我以前试过。你确定root.getChildren()
的行为符合预期吗?findAHelper(这个,id)
应该类似于a=findAHelper(这个,id);如果(a!=null){returna;}
“这只在”否“时起作用,它不起作用,因为该代码不会编译,所以永远不会起作用。不,什么时候,如果,但是。