我有3种方法可以递归实现。是的,这是为学校准备的,所以请不要简单明了的答案,我希望有描述性的答案,以便我可以学习!我对树结构不熟悉。
这3种方法如下...
public class Zombies{
public static int countPeople(Person p){...}
// counts all the people in the tree structure
// starting with Person p.
public static int countZombies(Person p){...}
// counts all the people in the tree structure
// starting with Person p that are zombies
public static void draw(Person p){...}
// draws a diagram of the people in tree structure
// starting with Person p.
// each person will be denoted by a P and
// person that is a zombie will be denoted by a Z
//
// The diagram should illustrate the family tree
// structure. Each person will be drawn with 3 minus
// signs '-' for each level below p.
我已经开始了我的人物类(class),我有几个问题。
1)我的人员类别是否走在正确的轨道上
2)方法描述中提到的树结构是二叉树吗?
3)我缺少什么来实现这些方法(如果有什么东西,或者这个树结构是否需要构建 block )
下面是我的 Person 类。
public class Person{
public int id; // some identification number unique to the person
public boolean zombie; // true if the person is a zombie
public char state; // p means human, z means zombie
public ArrayList<Person> friends; // list of friends
public Person(int id, char state, boolean zombie){
this.id = id;
this.state = state;
this.zombie = zombie;
}
public boolean isZombie() {
if (state == 'p'){
return zombie=false;
}
else if (state == 'z'){
return zombie=true;
}
return zombie;
}
}
树类型的示例输出如下..
P (this is Person q)
---P (this is a friend of q, say q1)
------P (this is a friend of q1)
------Z (this is another friend of q1, who is a zombie)
---Z (this is a friend of q, say q2, who is a zombie)
------Z (this is a friend of q1, who is also a zombie)
------P (this is a friend of q1, who is not a zombie)
预先感谢您的耐心和帮助/意见!
最佳答案
1)也许不是您正在寻找的内容,但我会摆脱 Person.state
。有两个单独的字段都用于确定一个人是否是僵尸是令人困惑且容易出错的。当 zombie
为 true
且 state
为 p
时,这意味着什么?
2) Miorel 的评论有一些很好的见解。从你给我们的信息来看,我们并不清楚这棵树应该代表什么,为什么它必须是一棵树,或者它是如何填充的。
3)您需要某种世界对象。 僵尸
可能是一个不错的选择。显然,在某个地方,你需要一棵所有人的树。至少,你需要某种程度的人员集合。该集合需要声明、实例化和填充。您可能希望它作为 Zombies
类的成员。绝对不是作为 Person
类的成员,您将拥有很多这样的类。
关于java - Java中基于ArrayList的二叉树实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15751985/