简体   繁体   中英

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

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.

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, eg adoption. "Father" and "mother" is almost certainly too simplistic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM