计算一棵树的孙子数

时间:2010-11-06 21:48:23

标签: java recursion tree

  

可能重复:
  Stop recursion after a certain amount of steps

这种方法在计算树中的孙子数量时会出现什么问题,而不是曾孙子孙女?

(child1是left child,child2是right child)另外,这个方法不应该带任何参数。如果您提供替代解决方案,请告诉我目前的解决方案有什么问题。

  public int countGrandChildren() // but not greatGrandChildren
    {
        int count=0;
        int depth=1;
        if (depth<4){
            if (child1!=null){
                count+=child1.countGrandChildren();
                depth++;
                if (depth==3)
                    count++;
            }
            if (child2!=null){
                count+=child2.countGrandChildren();
                depth++;
                if (depth==3)
                    count++;    
            }   
        }
        return count;

    }

3 个答案:

答案 0 :(得分:0)

如果您没有将深度传递给每个递归调用,这将如何工作?开始时深度始终为1,然后您可以增加深度。但它永远不会== 3。

答案 1 :(得分:0)

正如在your previous question已经讨论过的那样,你没有在连续的递归调用之间传递任何参数,那么它们怎么可能终止呢?

int depth = 1; if (depth < 4) ... 总是是这样的!

解决方案是以下其中一种可能性的变体:

  • 递归传递depth(或等效)参数
  • 将计数保持在其他地方(糟糕)
  • 根据其在树中的位置为构造中的myDepth成员变量分配一个{{1}}成员变量(如果您需要重新排列树中的项目,这将是一个痛苦的事情)

答案 2 :(得分:0)

你最好的选择是传递深度变量作为函数的参数这里是一个更简单的例子,通过递归调用函数计算数字的阶乘,但每次传递的参数减去1。

public int calcFactorial(int facnum){
    int res;
    if (facnum==1){
        res=1;
        }
     else {
        res=facnum*calcFactorial(facnum-1);
        }        

}
相关问题