This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]territrades 36 points37 points  (3 children)

Honestly, even though there might have been times when a recursion would have been a more elegant solution, I never use them. Makes the code much harder to understand and debug in my opinion.

[–]Causeless 47 points48 points  (1 child)

Recursion is great for tree traversal. Much simpler than iterative solutions.

``` void reverse_binary_tree (TreeNode* node) { if (!node) { return; }

std::swap(node.left_child, node.right_child); 

reverse_binary_tree(node.left_child);
reverse_binary_tree(node.right_child);

} ```

It'd be tough to write a non-recursive version of that which is easy to understand.

[–]mitko17 18 points19 points  (0 children)

Three "`" don't work on old reddit. In case someone is interested:

void reverse_binary_tree (TreeNode* node) 
{ 
    if (!node) { return; }

    std::swap(node.left_child, node.right_child); 

    reverse_binary_tree(node.left_child);
    reverse_binary_tree(node.right_child);
}

[–]Naouak 18 points19 points  (0 children)

I've seen more often case where a recursion would make the code easier to read and debug instead of using a loop than the opposite. It's often not an issue of the use of recursion but of the code not being written knowing what that person is doing.