Print relationships to a PrintWriter instead of a StringBuilder, and use a stack to avoid cycles.