【问题标题】:Help with tree recursion帮助树递归
【发布时间】:2010-11-08 20:19:10
【问题描述】:

我有一个 Person 类,我想创建一棵树。这是 Person 类的构造函数。

public Person(String name, int age, char gender, Person c1, Person c2)

c1 是左边的孩子,c2 是右边的孩子。假设我创建了三个像这样的人:

Person c = new Person("Carl", 50, 'M', null, f);

Person b = new Person("Barbara", 52, 'F', d, e);

Person a = new Person("Adam", 75, 'M', b, c);

所以在这里你说亚当是根节点,亚当的左孩子是 b,也就是芭芭拉,他的右孩子是卡尔,以此类推。

所以我想做的是写一个计数方法,计算包括this在内的孩子的数量。所以 a.count() 将返回 6 (如果 Person f 没有任何孩子)。

这是我的代码:

public int count() // total person count including this object
{
    if(child1==null)
        return 0; //I tried return 1 for this too didnt work
    if (child2==null)
        return 0; //also tried 1 for this
    return 1+this.child1.count() +1+this.child2.count();
}

我在纸上运行了几次,它应该会得出正确的结果,但是当我实际运行它时,由于某种原因它有一些偏差。

【问题讨论】:

    标签: java recursion tree


    【解决方案1】:

    如果其中一个孩子是null,您的代码将返回0。这是不正确的,因为您没有考虑其他孩子或this。计数应始终为 >= 1,因为树中始终至少有一个节点。

    另外,如果您看到一个孩子是null,您也不能立即返回。您也需要计算另一个孩子(如果存在)。

    这是我将如何实现它:

    public int count() // total person count including this object
    {
        int count = 1; // we count this node as 1 
        if (child1 != null) // if we have a left child, count its size
            count += child1.count();
        if (child2 != null) // if we have a right child, count its size
            count += child2.count()
        return count;
    }
    

    您需要考虑这两个孩子,即使其中一个是null

    【讨论】:

    • @fprime,如果其中一个孩子是null,您的代码将返回 0。这是不正确的,因为您没有考虑到另一个孩子或this
    • 最初我有 if null return 1 for both,这也不起作用,即使它也应该有。为什么那行不通
    • @fprime,因为如果一个孩子为空,您不能只返回。您还必须计算其他孩子。 (见我的更新)
    • @fprime:如果 child1 为 null,则立即返回 0。您不计算 child2 的子节点数,也不计算节点本身。
    • 哦,好吧,我明白了..所以我的代码“逻辑”是正确的,但我没有检查两个孩子的事实是问题所在?所以如果我把count+=child1.count()换成count=1+child1.count(),会不会一样?
    【解决方案2】:

    结果是错误的,因为当一个子节点为空而忘记计算节点本身或另一个子节点时,您返回 0。如果它是叶节点 (child1 == null && child2 == null),您无论如何都应该返回 1。

    类似:

    return 1 + (child1 == null ? 0 : child1.count()) + (child2 == null ? 0 : child2.count())
    

    按照您的原始代码,它会是这样的:

    if (child1 == null && child2 == null)
      return 1;
    else if (child1 == null)
      return 1 + child2.count();
    else if (child2 == null)
      return 1 + child1.count();
    else
      return 1 + child1.count() + child2.count();
    

    但在这种情况下,我会说坚持使用 jjnguy 答案,它会部分计算结果..

    【讨论】:

    • 令人印象深刻但复杂的代码大声笑你能把它变成 if else 语句/
    【解决方案3】:
    private int count() {
        return 1 + ((this.child1 != null) ? (this.child1.count()) : (0)) + ((this.child2 != null) ? (this.child2.count()) : (0));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-21
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-09
      • 1970-01-01
      相关资源
      最近更新 更多