Say I have a Javascript data structure such as:
var data = {
id: '5551212',
children: [
{id: '5551213'},
{id: '5551214'},
{
id: '5551215',
children: [
{id: '5551213'},
{id: '5551212'} // <--- I want to detect THIS one! It's a recursive entry.
// or a similar occurrence anywhere in the tree.
]}
]
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm looking for a general algorithm to detect a "recursive" item such as the one shown. I find that it's easy enough if the recursive item is just below the "parent" but what if the duplication can occur anywhere?
In this case these are mechanical assembly part numbers. So while it's no problem creating a data structure like this, actually building a recursive assembly is impossible. So I need to find a potential mistake on the user's part before they try to build something impossible.
When searching for algorithms, all I'm getting are recursive programming examples and discussions or here on StackOverflow most questions seem to be about how to create such a recursive structure.
I'm working in Javascript w/ JQuery but I'm looking for an applicable algorithm here, not necessarily an implementation.