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.


Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of