Avatar ·

Cycles in a family tree: how to detect and prevent invalid relationships?

Hi everyone! I'm writing a program for building a family tree in C++. I've encountered a problem where a user accidentally creates a cycle in the relationships (for example, making their ancestor their descendant). This breaks all the display and kinship calculation logic. I have a structure for the tree node: ```cpp struct Person { string name; Person* father; Person* mother; vector children; }; ``` I add a "parent-child" relationship through a function: ```cpp void addChild(Person* parent, Person* child) { parent->children.push_back(child); if (child->father == nullptr) child->father = parent; else if (child->mother == nullptr) child->mother = parent; // Problem: not checking if child is an ancestor of parent } ``` How do I implement cycle detection?