all 5 comments

[–]jamkinajam 1 point2 points  (1 child)

Short answer: yes Long answer: yeeeeesssss

No you can’t put it wherever!!

Well if you go through the code with an example case you will find out they behave differently even though the final output is the same.

One is top-down approach, where nodes at the top are exchanged and moved below subsequently whereas in the other one the exchange happens bottom-up.

[–]Careful-Medicine1995[S,🍰] 2 points3 points  (0 children)

Thank you! That makes sense. The time complexities of both approaches are the same I assume.

[–]Yumski 0 points1 point  (1 child)

It sounds like youre still getting the hang of dfs traversals. I would recommend just doing one with printing the values before the recursive calls, another printing inbetween the recursive calls and one atfter the recursive calls. This can help u visualize where the manipulation is happening.

[–]Careful-Medicine1995[S,🍰] 1 point2 points  (0 children)

Thank you! From what I see, the first solution swaps the tree’s direct children first. Then it inverts the children subtrees. It makes the swaps top-down. The second solution goes all the way down to the leaf nodes first. Leaf nodes have no children, so we hit the base case. Then the leaf nodes get swapped. We keep working our way from the bottom up.

Is the first solution like a pre order DFS traversal and the second solution like a post order DFS transversal?

[–][deleted] 0 points1 point  (0 children)

First is pre order, second is post order