Mirroring a binary tree, a common question nowadays to understand whether the candidate knows about tree traversal. Asking plainly in-order/pre-order is of no use!! :)
The dummies way is to directly jump to code which never works even for such a simple problem.
First thought, i got this code:
Flaws in it?
- This is a mugged up code!!
- You didn’t think about whether to output the mirrored tree in a new data structure or to do it in-place
- Why you cannot use tail recursion for in-place,
- Reason 1: you need to swap left & right using a temporary storage. You need to expand the tree on the stack
- Reason 2: The above kind of swapping loses the node->left data whatever magic your recursion does.
Now, we got full of issues, think basic, non-iterative way
Whatever way you follow, you need to do the above swap.
Corrected code for reproduction of mirrored tree, as a copy
Correct code for creating mirrored tree, in-place
- do a post order traversal to read the full tree into the recursion stack
- do the primitive swap operation