I have some code that creates a ancestor tree created from data files uploaded by users. But in some cases there are logical errors in these trees. Like in the picture below. The situation in the red box creates a infinite loop while creating the tree.
My question is how to detect this situation when creating a tree an break the reading. The code is just a ordinary recursive function that traverse the tree, I start with the first person, then get the parents, and so on until there are no more ancestors in the tree.
First I was thinking that I could just have a flat list with all people added and check if they already exists in the tree. But that dont work since its OK for one person to exist several times, like shown in the two green boxes. Inbreeding occures.
Is there any ways to detect a infinite loop in a tree to avoid the "red situation" in the picture? Tree with infinite loop
EDIT: Maybe this picture clarifies what I need to detect. The blue dots are the same persons, and the tree above this is by logic also the same persons as the blue tree to the side. This is a functionality that I would like to keep since it dont create a infinite loop. But if the data does like the red arrow, then it becomes a infinite loop, and this is the scenario I would like to detect, but keep the blue trees. Tree with OK scenario