Given a binary tree, write an efficient algorithm to convert the binary tree into its mirror.

For example, the following binary trees are mirrors of each other:

Binary Tree Mirror

Practice this problem

The idea is simple – traverse the tree in a postorder fashion, and for every node, swap its left and right child pointer after recursively converting its left and right subtree to mirror first. Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

1 3 7 6 2 5 4

Java


Download  Run Code

Output:

1 3 7 6 2 5 4

Python


Download  Run Code

Output:

1 3 7 6 2 5 4

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The program requires O(h) extra space for the call stack, where h is the height of the tree.

 
Iterative version:

Invert Binary Tree – Iterative and Recursive Solution