How can I build a basic tree of Objects from an ArrayList (in this case Person objects from my Person class below)? Conceptually I understand how the tree works, how to add Objects to my arraylist but I am having a lot of trouble with the building aspect of the tree and linking nodes together I seem to find overwhelming. Also, from the research i have done, it seems that a recursvie algorithm is the best way to tackle this. Is it true? I am a beginner in Java so please a detailed answer and not just code would be appreciated.
Here is the the Person class i have and which the objects in the tree i want to base it from.
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;
}
Thanks in advance for any input and explanations. It is greatly appreciated!
below is sample output and demonstrates the desired hierarchy of the tree
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 like to create the tree structure so that there are no cross-links. Each Person in the tree structure can exist in only one friend's list and there will be one Person that is in no ones friend's list (the root of the tree). and each friend can only have two friends. (i assume this is a binary tree)
Edit: Could I use the treemap that is provided by java?