The idea is to use recursion to traverse the tree in Post Order (left, right, root) and while traversing each node, swap the left and right subtrees.
Working of Approach:
Start from the root node.
Recursively mirror the left subtree.
Recursively mirror the right subtree.
Swap the left and right child of the current node.
Continue until all nodes are processed.
C++
#include<iostream>#include<queue>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Function to convert binary tree into its mirror tree.voidmirror(Node*root){// Base caseif(root==nullptr)return;// Mirror left subtreemirror(root->left);// Mirror right subtreemirror(root->right);// Swap left and right childswap(root->left,root->right);}voidprintLevelOrder(Node*root){if(!root){cout<<"[]";return;}vector<string>ans;queue<Node*>q;q.push(root);while(!q.empty()){Node*curr=q.front();q.pop();if(curr){ans.push_back(to_string(curr->data));q.push(curr->left);q.push(curr->right);}else{ans.push_back("N");}}// Remove trailing nullswhile(!ans.empty()&&ans.back()=="N")ans.pop_back();cout<<"[";for(inti=0;i<ans.size();i++){cout<<ans[i];if(i+1!=ans.size())cout<<", ";}cout<<"]";}intmain(){// root = [1, 2, 3, 4, 5]Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);mirror(root);printLevelOrder(root);return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}publicclassGFG{// Function to convert binary tree into its mirror tree.staticvoidmirror(Noderoot){// Base caseif(root==null)return;// Mirror left subtreemirror(root.left);// Mirror right subtreemirror(root.right);// Swap left and right childNodetemp=root.left;root.left=root.right;root.right=temp;}staticvoidprintLevelOrder(Noderoot){if(root==null){System.out.print("[]");return;}ArrayList<String>ans=newArrayList<>();Queue<Node>q=newLinkedList<>();q.add(root);while(!q.isEmpty()){Nodecurr=q.poll();if(curr!=null){ans.add(Integer.toString(curr.data));q.add(curr.left);q.add(curr.right);}else{ans.add("N");}}// Remove trailing nullswhile(!ans.isEmpty()&&ans.get(ans.size()-1).equals("N"))ans.remove(ans.size()-1);System.out.print("[");for(inti=0;i<ans.size();i++){System.out.print(ans.get(i));if(i+1!=ans.size())System.out.print(", ");}System.out.print("]");}publicstaticvoidmain(String[]args){// root = [1, 2, 3, 4, 5]Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);mirror(root);printLevelOrder(root);}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=self.right=None# Function to convert binary tree into its mirror tree.defmirror(root):# Base caseifrootisNone:return# Mirror left subtreemirror(root.left)# Mirror right subtreemirror(root.right)# Swap left and right childroot.left,root.right=root.right,root.leftdefprint_level_order(root):ifrootisNone:print('[]')returnans=[]q=deque([root])whileq:curr=q.popleft()ifcurr:ans.append(str(curr.data))q.append(curr.left)q.append(curr.right)else:ans.append('N')# Remove trailing nullswhileansandans[-1]=='N':ans.pop()print('['+', '.join(ans)+']')if__name__=='__main__':# root = [1, 2, 3, 4, 5]root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)mirror(root)print_level_order(root)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGFG{// Function to convert binary tree into its mirror tree.staticvoidmirror(Noderoot){// Base caseif(root==null)return;// Mirror left subtreemirror(root.left);// Mirror right subtreemirror(root.right);// Swap left and right childNodetemp=root.left;root.left=root.right;root.right=temp;}staticvoidPrintLevelOrder(Noderoot){if(root==null){Console.Write("[]");return;}List<string>ans=newList<string>();Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){Nodecurr=q.Dequeue();if(curr!=null){ans.Add(curr.data.ToString());q.Enqueue(curr.left);q.Enqueue(curr.right);}else{ans.Add("N");}}// Remove trailing nullswhile(ans.Count>0&&ans[ans.Count-1]=="N")ans.RemoveAt(ans.Count-1);Console.Write("[");for(inti=0;i<ans.Count;i++){Console.Write(ans[i]);if(i+1!=ans.Count)Console.Write(", ");}Console.Write("]");}staticvoidMain(string[]args){// root = [1, 2, 3, 4, 5]Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);mirror(root);PrintLevelOrder(root);}}
JavaScript
classNode{constructor(x){this.data=x;this.left=this.right=null;}}// Function to convert binary tree into its mirror tree.functionmirror(root){// Base caseif(root===null)return;// Mirror left subtreemirror(root.left);// Mirror right subtreemirror(root.right);// Swap left and right childlettemp=root.left;root.left=root.right;root.right=temp;}functionprintLevelOrder(root){if(root===null){console.log("[]");return;}letans=[];letq=[root];while(q.length>0){letcurr=q.shift();if(curr!==null){ans.push(curr.data.toString());q.push(curr.left);q.push(curr.right);}else{ans.push("N");}}// Remove trailing nullswhile(ans.length>0&&ans[ans.length-1]==="N")ans.pop();console.log("["+ans.join(", ")+"]");}// Driver Code// root = [1, 2, 3, 4, 5]letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);mirror(root);printLevelOrder(root);
Output
[1, 3, 2, N, N, 5, 4]
Iterative BFS using Queue - O(n) Time and O(n) Space
The idea is to perform level order traversal (using a queue). For every node, swap its left and right children. This way, after processing all nodes, the tree becomes its mirror.
Working of Approach:
Push the root node into a queue.
Remove one node at a time from the queue.
Swap its left and right child.
Push the existing children into the queue.
Continue until the queue becomes empty.
Let us understand with an example: Input: root = [1, 2, 3, 4, 5]
Create the binary tree: 1 as root, 2 and 3 as its children, and 4, 5 as children of 2.
Start BFS from the root. For each visited node, swap its left and right children and push the updated children into the queue.
After processing all nodes, the tree becomes: 1 -> left 3, right 2; and 2 -> left 5, right 4.
Perform level-order traversal of the mirrored tree while including N for missing children and removing trailing Ns.
Final output is [1, 3, 2, N, N, 5, 4].
C++
#include<iostream>#include<queue>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Function to convert binary tree into its mirror tree.voidmirror(Node*root){// If tree is emptyif(root==nullptr)return;queue<Node*>q;q.push(root);while(!q.empty()){// Get the front nodeNode*curr=q.front();q.pop();// Swap left and right childswap(curr->left,curr->right);// Push left childif(curr->left)q.push(curr->left);// Push right childif(curr->right)q.push(curr->right);}}voidprintLevelOrder(Node*root){if(!root){cout<<"[]";return;}vector<string>ans;queue<Node*>q;q.push(root);while(!q.empty()){Node*curr=q.front();q.pop();if(curr){ans.push_back(to_string(curr->data));q.push(curr->left);q.push(curr->right);}else{ans.push_back("N");}}// Remove trailing nullswhile(!ans.empty()&&ans.back()=="N")ans.pop_back();cout<<"[";for(inti=0;i<ans.size();i++){cout<<ans[i];if(i+1!=ans.size())cout<<", ";}cout<<"]";}intmain(){// root = [1, 2, 3, 4, 5]Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);mirror(root);printLevelOrder(root);return0;}
Java
importjava.util.*;// Structure of a binary tree nodeclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}publicclassGFG{// Function to convert binary tree into its mirror tree.staticvoidmirror(Noderoot){// If tree is emptyif(root==null)return;Queue<Node>q=newLinkedList<>();q.offer(root);while(!q.isEmpty()){// Get the front nodeNodecurr=q.poll();// Swap left and right childNodetemp=curr.left;curr.left=curr.right;curr.right=temp;// Push left childif(curr.left!=null)q.offer(curr.left);// Push right childif(curr.right!=null)q.offer(curr.right);}}staticvoidprintLevelOrder(Noderoot){if(root==null){System.out.print("[]");return;}ArrayList<String>ans=newArrayList<>();Queue<Node>q=newLinkedList<>();q.offer(root);while(!q.isEmpty()){Nodecurr=q.poll();if(curr!=null){ans.add(String.valueOf(curr.data));q.offer(curr.left);q.offer(curr.right);}else{ans.add("N");}}// Remove trailing nullswhile(!ans.isEmpty()&&ans.get(ans.size()-1).equals("N"))ans.remove(ans.size()-1);System.out.print("[");for(inti=0;i<ans.size();i++){System.out.print(ans.get(i));if(i+1!=ans.size())System.out.print(", ");}System.out.print("]");}publicstaticvoidmain(String[]args){// root = [1, 2, 3, 4, 5]Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);mirror(root);printLevelOrder(root);}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to convert binary tree into its mirror tree.defmirror(root):# If tree is emptyifrootisNone:returnq=deque()q.append(root)whilelen(q)>0:# Get the front nodecurr=q.popleft()# Swap left and right childcurr.left,curr.right=curr.right,curr.left# Push left childifcurr.leftisnotNone:q.append(curr.left)# Push right childifcurr.rightisnotNone:q.append(curr.right)defprint_level_order(root):ifrootisNone:print("[]")returnans=[]q=deque()q.append(root)whilelen(q)>0:curr=q.popleft()ifcurrisnotNone:ans.append(str(curr.data))q.append(curr.left)q.append(curr.right)else:ans.append("N")# Remove trailing nullswhilelen(ans)>0andans[-1]=="N":ans.pop()print("["+", ".join(ans)+"]")if__name__=='__main__':# root = [1, 2, 3, 4, 5]root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)mirror(root)print_level_order(root)
C#
usingSystem;usingSystem.Collections.Generic;// Structure of a binary tree nodeclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGFG{// Function to convert binary tree into its mirror tree.staticvoidmirror(Noderoot){// If tree is emptyif(root==null)return;Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){// Get the front nodeNodecurr=q.Dequeue();// Swap left and right childNodetemp=curr.left;curr.left=curr.right;curr.right=temp;// Push left childif(curr.left!=null)q.Enqueue(curr.left);// Push right childif(curr.right!=null)q.Enqueue(curr.right);}}staticvoidPrintLevelOrder(Noderoot){if(root==null){Console.Write("[]");return;}List<string>ans=newList<string>();Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){Nodecurr=q.Dequeue();if(curr!=null){ans.Add(curr.data.ToString());q.Enqueue(curr.left);q.Enqueue(curr.right);}else{ans.Add("N");}}// Remove trailing nullswhile(ans.Count>0&&ans[ans.Count-1]=="N")ans.RemoveAt(ans.Count-1);Console.Write("[");for(inti=0;i<ans.Count;i++){Console.Write(ans[i]);if(i+1!=ans.Count)Console.Write(", ");}Console.Write("]");}staticvoidMain(string[]args){// root = [1, 2, 3, 4, 5]Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);mirror(root);PrintLevelOrder(root);}}
JavaScript
// Structure of a binary tree nodefunctionNode(x){this.data=x;this.left=null;this.right=null;}// Function to convert binary tree into its mirror tree.functionmirror(root){// If tree is emptyif(root===null)return;letq=[];q.push(root);while(q.length>0){// Get the front nodeletcurr=q.shift();// Swap left and right childlettemp=curr.left;curr.left=curr.right;curr.right=temp;// Push left childif(curr.left)q.push(curr.left);// Push right childif(curr.right)q.push(curr.right);}}functionprintLevelOrder(root){if(!root){console.log("[]");return;}letans=[];letq=[];q.push(root);while(q.length>0){letcurr=q.shift();if(curr){ans.push(curr.data.toString());q.push(curr.left);q.push(curr.right);}else{ans.push("N");}}// Remove trailing nullswhile(ans.length>0&&ans[ans.length-1]==="N")ans.pop();console.log("["+ans.join(", ")+"]");}// Driver Code// root = [1, 2, 3, 4, 5]letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);mirror(root);printLevelOrder(root);