I suspect there's something else going on here, or your comments data is far different than I'm supposing.
Your flatten method works just fine for me with a tree of 600 comments. In fact, it works fine with 600,000 comments (recurs. lim. 1000)
Example test script:
https://pastebin.com/6Mdvu2WL
Without seeing your other code, I don't know what the issue you're running into. At a wild guess, is it possible your graph is not acyclic?