我需要一个类Person描述者。每个人都有一个名字和由人的对象,它代表了人的孩子组成的数组。 Person类有一个方法getNumberOfDescendants,它返回等于人的后代的总数的整数,即他的子女加加上孙辈子女等有没有一种简单的方法来做到这一点使用递归?

如果您希望只在某一代来算的后代怎么办?换句话说,getNumberOfDescendants(INT代)将返回的孩子们的号码,如果代= 1,孙子女的号码,如果代= 2等

有帮助吗?

解决方案

不确定

public class Person {

private Person[] myChildren;

public int getNumberOfDescendants() {
  if (myChildren == null || myChildren.length==0) return 0;
  int myDescendants = 0;
  for (Person child:myChildren) {
    myDescendants += 1; // for this particular child itself
    myDescendants += child.getNumberOfDescendants();  //add the child's children, grandchildren, etc.
  }
  return myDescendants;
}

}

其他提示

getNumberOfDescendants()
{
  int sum = 0;
  for (int n=0; n < descendants.length; n++)
  {
    sum += 1 + descendants[n].getNumberOfDescendants();
  }
  return sum;
}

请注意,“1 +”是唯一的地方,我们实际上增加了计数。该行获取树中的每一个后代调用一次。

这不是一个真正的递归本身,而是一个类的实例可以总结调用getNumberOfDescendants()方法,它的每个孩子的结果。

另外,你可以把这个方法更快的通过使每个实例通知其父每当有一个新的后代(无论是新的孩子或由孩子被通知)。这样一来,它的后代的数量的计数将始终保持为最新。

  public int getNumberDescendents()
  {
    int nDesc = 0;
    if (descendants != null)
    {
      for (Person p : descendants)
      {
        nDesc++; // this child
        nDesc += p.getNumberDescendents(); // this child's desc
      }
    }
    return nDesc;
  }

这是我写的例子起来的时候,其他人基本上张贴同样的事情,所以我也有点冗余发布。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top