我如何从 ArrayList 构建一个基本的对象树(在本例中是来自下面我的 Person 类的 Person 对象)?从概念上讲,我理解树是如何工作的,如何将对象添加到我的数组列表中,但是我在树的构建方面和将节点链接在一起时遇到了很多麻烦,我似乎感到不知所措。此外,从我所做的研究来看,recursvie 算法似乎是解决此问题的最佳方法。是真的吗?我是 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 喜欢创建树结构,这样就没有交叉链接。树结构中的每个 Person 只能存在于一个 friend 列表中,并且会有一个 Person 不在任何 friend 列表中(树的根)。而且每个 friend 只能有两个 friend 。 (我假设这是一个二叉树)
编辑:我可以使用 java 提供的 TreeMap 吗?
最佳答案
也许我遗漏了什么,但 ArrayList(或一般的列表)与任务有什么关系?如果任何人都可以链接到许多人,那么它就是一个图表。例如。它可能有像 A->B->C->A 这样的循环,您无法使用树来表示。
一个人有一个 friend 列表这一事实意味着图中的一个节点可以链接到任意数量的其他节点。
所以我认为你应该构建一个图表。
如果您想删除重复链接(例如 A->B、B->A),请将其作为后处理步骤执行。
关于java - 构建 ArrayList 树 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15789207/