The topological ordering something can be unclear in this type. So recursion + memoization might the way to go.