Best way of implementing a family tree in Java using a data structure

Tj895 picture Tj895 · Sep 14, 2015 · Viewed 7.3k times · Source

https://softwareengineering.stackexchange.com/questions/285418/name-of-data-structure-thats-tree-like-with-multiple-root-nodes

I stumbled upon the above where someone answered a question regarding implementing a tree that has > 2 nodes and I just wanted to get someone's thoughts on how best to implement a family tree with parent nodes which have more than two children nodes. I had looked in Binary Trees, but since they can only have two children nodes decided to research elsewhere. I also looked into using a Forest Data Structure to implement a Family Genealogy Tree that consist of multiple nodes with 0-multiple children. Possibly may use a Forest Tree, however from most representations that I searched up on and found, it looks similar to a disjointed set, but I do not want a parent node to already be pre-destined to have no children. I hope it makes sense what I am saying. Any advice or comments anyone is able to offer would be much appreciated.

Answer

Andy Turner picture Andy Turner · Sep 14, 2015

If you want to represent a list of children, simply have a list of Person instances inside your Person class:

class Person {
  List<Person> children;
  Person father;
  Person mother;
}

Then you can add as many Persons as you want to the children list.

I also added father and mother fields here to allow you to navigate to parents.

One tip: Be very thorough with your modelling. Familial relations have some easy to miss cases, e.g. adoption. "Father" and "mother" is almost certainly too simplistic.