【发布时间】: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();
}
我在纸上运行了几次,它应该会得出正确的结果,但是当我实际运行它时,由于某种原因它有一些偏差。
【问题讨论】: