• tatterdemalion@programming.dev
    link
    fedilink
    arrow-up
    2
    ·
    edit-2
    11 months ago

    I’ve found that it’s usually best to keep it iterative if it can be done with a simple data structure, like stack (DFS) or queue (BFS). But that’s not always a simple task.

    One common case where recursion is actually more natural is post-order tree traversals. For example if you had a tree where every node held a number and you wanted to calculate the sum of each node’s descendants. This is natural with recursion because a node is able to directly sum the values returned from recursive calls. Doing this with an explicit stack would be awkward, because you don’t usually get to visit a node twice (once to put children on the stack, once again to accumulate the descendants sum).

    Like, just look how weird this algorithm is: https://www.geeksforgeeks.org/iterative-postorder-traversal-using-stack/ I don’t think I’ve ever done it this way.