Consider the following version of your schedule ...
A | X---B---Y \ / \ / CE | | DF \ / G
nodes = {"G", "F", "E", "D", "C", "B", "A", "X", "Y"}
parentNodes = {{"F","D"},{"E"}, {"Y","B"}, {"C"}, {"X","B"}, {"A"}, null, {"B"}, {"B"}}
I think that your program encountered difficulty when it gets to node "C" , because it has two parents nodes for study. You need to either resort to a recursive algorithm or manage some kind of stack for unexplored nodes using an iterative algorithm.
Since you have a bias for the iterator, you can try something like this:
Create an array (or similar data structure). Each element of the array contains three pieces of information:
nodeName: string - name of a node from your `nodes` string pathLength[2]: integer - array of minimum path length from refrence node (1 or 2).
Create a stack. Each stack element contains three pieces of information:
nodeName: string - name of a node to "explore" lengthToHere: integer - length of path from reference node to `nodeName` pathNumber: integer - 1 for first reference node, 2 for second.
Algorithm:
Initialize array with nodeName from nodes and set each pathLength to "infinity" Push both starting reference nodes onto the stack: push("F", 0, 1) push "D", 0, 2) Repeat until stack is empty: - pop(nodeName, lengthToHere, pathNumber) - update pathLength[pathNumber] of element having nodeName in array with minimum of its current value and lengthToHere - for each parent of nodeName push(parent, lengthToHere + 1, pathNumber)
The stack is empty when all paths from the initial reference nodes have been evaluated. If there is a common ancestor and pathLength values ​​for this nodeName will be less than infinity. Add these values ​​together to give the total path length to this common ancestor. Provide the node name with the smallest amount.