Explanation: In the flip operation, the leftmost node becomes the root of the flipped tree and its parent becomes its right child and the right sibling becomes its left child and the same should be done for all leftmost nodes recursively.
[Expected Approach - 1] Using Recursion - O(n) Time and O(n) Space
The idea is to recursively flip the binary tree by swapping the left and right subtrees of each node. After flipping, the tree's structure will be reversed, and the new root of the flipped tree will be the original leftmost leaf node.
Below is the implementation of the above approach:
Output
2
3 1
4 5
[Expected Approach - 2] Iterative Approach - O(n) Time and O(n) Space
The iterative solution follows the same approach as the recursive one, the only thing we need to pay attention to is saving the node information that will be overwritten.
Below is the implementation of the above approach: