递归地找到一个元素

时间:2016-05-11 00:52:34

标签: java recursion

我有一个看起来像树的数据结构:

A -> A 
  -> A
  -> A -> A -> A
       -> A
       -> A
       -> A

基本上A可以由另一个A或多个A(s)组成。

我想找一个带有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那么它将无法工作。这是因为我没有正确回归。请帮忙。

2 个答案:

答案 0 :(得分:2)

您需要在findParticularA中返回findAHelper的结果。

findAHelper中,循环使你深入到树的三个分支;希望A会从这些分支中恢复,但它不会从所有分支中回来,只有一个。其余的(或全部)将返回null。

所以你需要捕获findAHelper的返回值,看看它是否为null,以决定是否返回它 - 如果它是A(非空),则返回它,否则不要#39; t让循环继续下一个树枝。

我无法在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;
}

答案 1 :(得分:2)

您可以使用一种方法执行此操作。您不需要findParticularA

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;
}

只需拨打:

A a = findA(this, id);
相关问题