java - Java中基于ArrayList的二叉树实现

标签 java oop recursion arraylist tree

我有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。有两个单独的字段都用于确定一个人是否是僵尸是令人困惑且容易出错的。当 zombietruestatep 时,这意味着什么?

2) Miorel 的评论有一些很好的见解。从你给我们的信息来看,我们并不清楚这棵树应该代表什么,为什么它必须是一棵树,或者它是如何填充的。

3)您需要某种世界对象。 僵尸可能是一个不错的选择。显然,在某个地方,你需要一棵所有人的树。至少,你需要某种程度的人员集合。该集合需要声明、实例化和填充。您可能希望它作为 Zombies 类的成员。绝对不是作为 Person 类的成员,您将拥有很多这样的类。

关于java - Java中基于ArrayList的二叉树实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15751985/

相关文章:

c++ - 当指向基类的指针指向特定子类时有条件地中断的断点

recursion - 实现最后一个非零而不延续

python - 正则表达式:如何捕获其中包含空格的大数字?

c - 使用具有返回类型的递归函数在 C 中进行二分搜索

java - 向ListView添加标题时出现空指针

java - 泛化类和继承问题

ruby - 类对象,单例类

java - Jsoup 不从 HTML 中解析 IFrame

java - 如何使用 thymeleaf 作为模板引擎生成 pdf 报告?

java - 使用java提取*.b64文件