Convert binary tree to its mirror

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


For example, below binary trees are mirror of each other.

Binary Tree Mirror


The idea is very simple. We traverse the tree in postorder fashion and for every node we swap its left and right child pointer after recursively converting its left subtree and right subtree first to mirror. Below is the C++ implementation of the idea –


Download   Run Complete Code

The time complexity of above solution is O(n) and need O(h) extra space for the call stack where h is the height of the tree.


1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of