【发布时间】:2013-03-25 05:29:24
【问题描述】:
如何从 ArrayList 构建基本的对象树(在本例中是来自下面我的 Person 类的 Person 对象)?从概念上讲,我了解树是如何工作的,如何将对象添加到我的数组列表中,但是我在树的构建方面遇到了很多麻烦,并且将节点链接在一起我似乎觉得不知所措。此外,从我所做的研究来看,递归算法似乎是解决这个问题的最佳方法。这是真的吗?我是Java初学者,所以请详细回答,而不仅仅是代码。
这是我拥有的 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){
this.id = id;
this.state = state;
//this.zombie = 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)
id 喜欢创建树结构,这样就没有交叉链接。树结构中的每个人只能存在于一个朋友的列表中,并且会有一个人在没有人的朋友列表中(树的根)。每个朋友只能有两个朋友。 (我假设这是一棵二叉树)
编辑:我可以使用 java 提供的树形图吗?
【问题讨论】:
-
你为什么要从 ArrayList 到树?
-
@supersam654 我正在尝试从我的数组列表中的对象制作一棵树
-
你的树应该代表什么样的关系/层次结构?是朋友,朋友的朋友等等?
-
"让我们假设 Person 根是根" - 这里的问题是它们都是 Person 的实例,而不仅仅是根。另外,当 A 是 B 的朋友而 B 是 A 的朋友时会发生什么?你得到一个循环引用。即使对于经验丰富的开发人员来说,构建您需要的树也是一项棘手的任务。
-
列表如何成为树? List 是对象的列表,在您的情况下是 Person。有关基本树结构的信息,请参阅此 Stack Overflow 答案。 stackoverflow.com/a/3522481/300257
标签: java oop recursion arraylist tree