Given the root of binary tree, Convert it into its mirror. A mirror of a binary tree is another tree in which the left and right children of every non-leaf node are interchanged.
Example:
Input:
Output:
Explanation: In the inverted tree, every non-leaf node has its left and right child interchanged.
Input:
Output:
Explanation: In the inverted tree, every non-leaf node has its left and right child interchanged.
[Approach 1] Recursive Approach - O(n) Time and O(n) Space
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.
C++
#include<iostream>#include<queue>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// function to return the root of inverted treevoidmirror(Node*root){if(root==nullptr)return;// Invert the left and right subtreemirror(root->left);mirror(root->right);swap(root->left,root->right);}intgetHeight(Node*root,inth){if(root==nullptr)returnh-1;returnmax(getHeight(root->left,h+1),getHeight(root->right,h+1));}voidlevelOrder(Node*root){queue<pair<Node*,int>>q;q.push({root,0});intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(!q.empty()){autotop=q.front();q.pop();Node*node=top.first;intlvl=top.second;if(lvl>lastLevel){cout<<"\n";lastLevel=lvl;}// all levels are printedif(lvl>height)break;if(node->data!=-1)cout<<node->data<<" ";// printing null nodeelsecout<<"N ";// null node has no childrenif(node->data==-1)continue;if(node->left==nullptr)q.push({newNode(-1),lvl+1});elseq.push({node->left,lvl+1});if(node->right==nullptr)q.push({newNode(-1),lvl+1});elseq.push({node->right,lvl+1});}}intmain(){// Input Tree:// 1// / \ // 2 3// / \ // 4 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);mirror(root);// Mirror Tree:// 1// / \ // 3 2// / \ // 5 4levelOrder(root);return0;}
C
#include<stdio.h>#include<stdlib.h>// Node StructurestructNode{intdata;structNode*left,*right;};structNode*createNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->left=NULL;node->right=NULL;returnnode;}// Queue implementation for struct Node*#define MAX_SIZE 100structQueue{structNode*items[MAX_SIZE];intfront,rear;};voidinitQueue(structQueue*q){q->front=0;q->rear=0;}intisEmpty(structQueue*q){returnq->front==q->rear;}voidenqueue(structQueue*q,structNode*node){if(q->rear<MAX_SIZE){q->items[q->rear++]=node;}}// Dequeue an itemstructNode*dequeue(structQueue*q){if(!isEmpty(q)){returnq->items[q->front++];}returnNULL;}voidswap(structNode**a,structNode**b){structNode*temp=*a;*a=*b;*b=temp;}voidmirror(structNode*root){if(root==NULL)return;// Invert the left and right subtreemirror(root->left);mirror(root->right);swap(&(root->left),&(root->right));}voidlevelOrder(structNode*root){if(root==NULL){printf("N ");return;}structQueueqq;initQueue(&qq);enqueue(&qq,root);while(!isEmpty(&qq)){structNode*curr=dequeue(&qq);if(curr==NULL){printf("N ");continue;}printf("%d ",curr->data);enqueue(&qq,curr->left);enqueue(&qq,curr->right);}}intmain(){// Input Tree:// 1// / \ // 2 3// / \ // 4 5structNode*root=createNode(1);root->left=createNode(2);root->right=createNode(3);root->left->left=createNode(4);root->left->right=createNode(5);mirror(root);// Mirror Tree:// 1// / \ // 3 2// / \ // 5 4levelOrder(root);return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;importjava.util.List;importjava.util.ArrayList;// Node StructureclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGFG{// Function to return the root of inverted treestaticvoidmirror(Noderoot){if(root==null)return;// Invert the left and right subtreemirror(root.left);mirror(root.right);Nodetemp=root.left;root.left=root.right;root.right=temp;}staticintgetHeight(Noderoot,inth){if(root==null)returnh-1;returnMath.max(getHeight(root.left,h+1),getHeight(root.right,h+1));}staticvoidlevelOrder(Noderoot){Queue<List<Object>>queue=newLinkedList<>();queue.offer(List.of(root,0));intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(!queue.isEmpty()){List<Object>top=queue.poll();Nodenode=(Node)top.get(0);intlvl=(int)top.get(1);if(lvl>lastLevel){System.out.println();lastLevel=lvl;}// all levels are printedif(lvl>height)break;// printing null nodeSystem.out.print((node.data==-1?"N":node.data)+" ");// null node has no childrenif(node.data==-1)continue;if(node.left==null)queue.offer(List.of(newNode(-1),lvl+1));elsequeue.offer(List.of(node.left,lvl+1));if(node.right==null)queue.offer(List.of(newNode(-1),lvl+1));elsequeue.offer(List.of(node.right,lvl+1));}}publicstaticvoidmain(String[]args){// Input Tree:// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);mirror(root);// Mirror Tree:// 1// / \// 3 2// / \// 5 4levelOrder(root);}}
Python
fromcollectionsimportdeque# Node StructureclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to return the root of inverted treedefmirror(root):ifrootisNone:return# Invert the left and right subtreemirror(root.left)mirror(root.right)root.left,root.right=root.right,root.left;defgetHeight(root,h):ifrootisNone:returnh-1returnmax(getHeight(root.left,h+1),getHeight(root.right,h+1))deflevelOrder(root):queue=deque([[root,0]])lastLevel=0# function to get the height of treeheight=getHeight(root,0)# printing the level order of treewhilequeue:node,lvl=queue.popleft()iflvl>lastLevel:print()lastLevel=lvl# all levels are printediflvl>height:break# printing null nodeprint("N"ifnode.data==-1elsenode.data,end=" ")# null node has no childrenifnode.data==-1:continueifnode.leftisNone:queue.append([Node(-1),lvl+1])else:queue.append([node.left,lvl+1])ifnode.rightisNone:queue.append([Node(-1),lvl+1])else:queue.append([node.right,lvl+1])if__name__=="__main__":# Input Tree:# 1# / \# 2 3# / \# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)mirror(root)# Mirror Tree:# 1# / \# 3 2# / \# 5 4levelOrder(root)
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGFG{staticvoidmirror(Noderoot){if(root==null)return;// Invert the left and right subtreemirror(root.left);mirror(root.right);Nodetemp=root.left;root.left=root.right;root.right=temp;}staticintgetHeight(Noderoot,inth){if(root==null)returnh-1;returnMath.Max(getHeight(root.left,h+1),getHeight(root.right,h+1));}staticvoidlevelOrder(Noderoot){Queue<(Node,int)>queue=newQueue<(Node,int)>();queue.Enqueue((root,0));intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(queue.Count>0){var(node,lvl)=queue.Dequeue();if(lvl>lastLevel){Console.WriteLine();lastLevel=lvl;}// all levels are printedif(lvl>height)break;// printing null nodeConsole.Write((node.data==-1?"N":node.data.ToString())+" ");// null node has no childrenif(node.data==-1)continue;if(node.left==null)queue.Enqueue((newNode(-1),lvl+1));elsequeue.Enqueue((node.left,lvl+1));if(node.right==null)queue.Enqueue((newNode(-1),lvl+1));elsequeue.Enqueue((node.right,lvl+1));}}staticvoidMain(){// Input Tree:// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);mirror(root);// Mirror Tree:// 1// / \// 3 2// / \// 5 4levelOrder(root);}}
JavaScript
// Queue nodeclassQNode{constructor(data){this.data=data;this.next=null;}}classQueue{constructor(){this.front=null;this.rear=null;}isEmpty(){returnthis.front===null;}enqueue(x){letnewNode=newQNode(x);if(this.rear===null){this.front=this.rear=newNode;return;}this.rear.next=newNode;this.rear=newNode;}dequeue(){if(this.front===null)returnnull;lettemp=this.front;this.front=this.front.next;if(this.front===null)this.rear=null;returntemp.data;}}// Node StructureclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to return the root of inverted treefunctionmirror(root){if(root===null)return;// Invert the left and right subtreemirror(root.left);mirror(root.right);lettemp=root.left;root.left=root.right;root.right=temp;}functiongetHeight(root,h){if(root===null)returnh-1;returnMath.max(getHeight(root.left,h+1),getHeight(root.right,h+1));}functionlevelOrder(root){letqueue=[];queue.push([root,0]);letlastLevel=0;// get the height of treeletheight=getHeight(root,0);// printing the level order of treewhile(queue.length>0){let[node,lvl]=queue.shift();if(lvl>lastLevel){console.log("");lastLevel=lvl;}// all levels are printedif(lvl>height)break;// printing null nodeprocess.stdout.write((node.data===-1?"N":node.data)+" ");// null node has no childrenif(node.data===-1)continue;if(node.left===null)queue.push([newNode(-1),lvl+1]);elsequeue.push([node.left,lvl+1]);if(node.right===null)queue.push([newNode(-1),lvl+1]);elsequeue.push([node.right,lvl+1]);}}// Driver Code// Input Tree:// 1// / \// 2 3// / \// 4 5letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);mirror(root);// Mirror Tree:// 1// / \// 3 2// / \// 5 4levelOrder(root);
Output
1
3 2
N N 5 4
[Approach 2] Iterative Approach - 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.
C++
#include<iostream>#include<queue>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};voidmirror(Node*root){if(root==nullptr)return;queue<Node*>q;q.push(root);// Traverse the tree, level by levelwhile(!q.empty()){Node*curr=q.front();q.pop();// Swap the left and right subtreeswap(curr->left,curr->right);// Push the left and right node to the queueif(curr->left!=nullptr)q.push(curr->left);if(curr->right!=nullptr)q.push(curr->right);}}intgetHeight(Node*root,inth){if(root==nullptr)returnh-1;returnmax(getHeight(root->left,h+1),getHeight(root->right,h+1));}voidlevelOrder(Node*root){queue<pair<Node*,int>>q;q.push({root,0});intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(!q.empty()){autotop=q.front();q.pop();Node*node=top.first;intlvl=top.second;if(lvl>lastLevel){cout<<"\n";lastLevel=lvl;}// all levels are printedif(lvl>height)break;if(node->data!=-1)cout<<node->data<<" ";// printing null nodeelsecout<<"N ";// null node has no childrenif(node->data==-1)continue;if(node->left==nullptr)q.push({newNode(-1),lvl+1});elseq.push({node->left,lvl+1});if(node->right==nullptr)q.push({newNode(-1),lvl+1});elseq.push({node->right,lvl+1});}}intmain(){// Input Tree:// 1// / \ // 2 3// / \ // 4 5Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);mirror(root);// Mirror Tree:// 1// / \ // 3 2// / \ // 5 4levelOrder(root);return0;}
C
#include<stdio.h>#include<stdlib.h>// Node structurestructNode{intdata;structNode*left;structNode*right;};// helper struct to store {node, start, end}structData{structNode*node;intstart;intend;};// queue element for Node + levelstructQueueNode{structNode*node;intlevel;structQueueNode*next;};// queue for DatastructDataQueueNode{structDatadata;structDataQueueNode*next;};// -------- Queue for levelOrder --------structQueueNode*createQueueNode(structNode*node,intlevel){structQueueNode*temp=(structQueueNode*)malloc(sizeof(structQueueNode));temp->node=node;temp->level=level;temp->next=NULL;returntemp;}voidenqueue(structQueueNode**front,structQueueNode**rear,structNode*node,intlevel){structQueueNode*temp=createQueueNode(node,level);if(*rear==NULL){*front=*rear=temp;return;}(*rear)->next=temp;*rear=temp;}structQueueNode*dequeue(structQueueNode**front,structQueueNode**rear){if(*front==NULL)returnNULL;structQueueNode*temp=*front;*front=(*front)->next;if(*front==NULL)*rear=NULL;returntemp;}intisQueueEmpty(structQueueNode*front){returnfront==NULL;}// -------- Queue for Data --------structDataQueueNode*createDataNode(structDatad){structDataQueueNode*temp=(structDataQueueNode*)malloc(sizeof(structDataQueueNode));temp->data=d;temp->next=NULL;returntemp;}voidenqueueData(structDataQueueNode**front,structDataQueueNode**rear,structDatad){structDataQueueNode*temp=createDataNode(d);if(*rear==NULL){*front=*rear=temp;return;}(*rear)->next=temp;*rear=temp;}structDatadequeueData(structDataQueueNode**front,structDataQueueNode**rear){structDataQueueNode*temp=*front;structDatad=temp->data;*front=(*front)->next;if(*front==NULL)*rear=NULL;free(temp);returnd;}intisDataQueueEmpty(structDataQueueNode*front){returnfront==NULL;}// -------- Node and Tree functions --------structNode*newNode(intdata){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=data;node->left=NULL;node->right=NULL;returnnode;}intgetHeight(structNode*root,inth){if(root==NULL)returnh-1;intleft=getHeight(root->left,h+1);intright=getHeight(root->right,h+1);return(left>right)?left:right;}voidlevelOrder(structNode*root){structQueueNode*front=NULL;structQueueNode*rear=NULL;enqueue(&front,&rear,root,0);intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(!isQueueEmpty(front)){structQueueNode*top=dequeue(&front,&rear);structNode*node=top->node;intlvl=top->level;free(top);if(lvl>lastLevel){printf("\n");lastLevel=lvl;}// all levels are printedif(lvl>height)break;if(node->data!=-1)printf("%d ",node->data);// printing null nodeelseprintf("%s ","N");// null node has no childrenif(node->data==-1)continue;if(node->left==NULL)enqueue(&front,&rear,newNode(-1),lvl+1);elseenqueue(&front,&rear,node->left,lvl+1);if(node->right==NULL)enqueue(&front,&rear,newNode(-1),lvl+1);elseenqueue(&front,&rear,node->right,lvl+1);}}structNode*sortedArrayToBST(intarr[],intn){if(n==0)returnNULL;// create the root node.intmid=(n-1)/2;structNode*root=newNode(arr[mid]);structDataQueueNode*front=NULL;structDataQueueNode*rear=NULL;structDatad={root,0,n-1};enqueueData(&front,&rear,d);while(!isDataQueueEmpty(front)){structDatacurrData=dequeueData(&front,&rear);structNode*curr=currData.node;intst=currData.start,en=currData.end;mid=(st+en)/2;// if left subtree existsif(st<mid){intleftVal=(st+mid-1)/2;structNode*left=newNode(arr[leftVal]);curr->left=left;structDatanewD={left,st,mid-1};enqueueData(&front,&rear,newD);}// if right subtree existsif(en>mid){intrightVal=(mid+1+en)/2;structNode*right=newNode(arr[rightVal]);curr->right=right;structDatanewD={right,mid+1,en};enqueueData(&front,&rear,newD);}}returnroot;}intmain(){intarr[]={1,5,9,14,23,27};intn=sizeof(arr)/sizeof(arr[0]);structNode*root=sortedArrayToBST(arr,n);levelOrder(root);return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;importjava.util.List;importjava.util.ArrayList;// Node StructureclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGFG{staticvoidmirror(Noderoot){if(root==null)return;Queue<Node>queue=newLinkedList<>();queue.add(root);// Traverse the tree, level by levelwhile(!queue.isEmpty()){Nodecurr=queue.poll();// Swap the left and right subtreeNodetemp=curr.left;curr.left=curr.right;curr.right=temp;// Push the left and right node to the queueif(curr.left!=null)queue.add(curr.left);if(curr.right!=null)queue.add(curr.right);}}staticintgetHeight(Noderoot,inth){if(root==null)returnh-1;returnMath.max(getHeight(root.left,h+1),getHeight(root.right,h+1));}staticvoidlevelOrder(Noderoot){Queue<List<Object>>queue=newLinkedList<>();queue.offer(List.of(root,0));intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(!queue.isEmpty()){List<Object>top=queue.poll();Nodenode=(Node)top.get(0);intlvl=(int)top.get(1);if(lvl>lastLevel){System.out.println();lastLevel=lvl;}// all levels are printedif(lvl>height)break;// printing null nodeSystem.out.print((node.data==-1?"N":node.data)+" ");// null node has no childrenif(node.data==-1)continue;if(node.left==null)queue.offer(List.of(newNode(-1),lvl+1));elsequeue.offer(List.of(node.left,lvl+1));if(node.right==null)queue.offer(List.of(newNode(-1),lvl+1));elsequeue.offer(List.of(node.right,lvl+1));}}publicstaticvoidmain(String[]args){// Input Tree:// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);mirror(root);// Mirror Tree:// 1// / \// 3 2// / \// 5 4levelOrder(root);}}
Python
fromcollectionsimportdeque# Node StructureclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=Nonedefmirror(root):ifrootisNone:returnqueue=deque([root])# Traverse the tree, level by levelwhilequeue:curr=queue.popleft()# Swap the left and right subtreecurr.left,curr.right=curr.right,curr.left# Push the left and right node to the queueifcurr.left:queue.append(curr.left)ifcurr.right:queue.append(curr.right)defgetHeight(root,h):ifrootisNone:returnh-1returnmax(getHeight(root.left,h+1),getHeight(root.right,h+1))deflevelOrder(root):queue=deque([[root,0]])lastLevel=0# function to get the height of treeheight=getHeight(root,0)# printing the level order of treewhilequeue:node,lvl=queue.popleft()iflvl>lastLevel:print()lastLevel=lvl# all levels are printediflvl>height:break# printing null nodeprint("N"ifnode.data==-1elsenode.data,end=" ")# null node has no childrenifnode.data==-1:continueifnode.leftisNone:queue.append([Node(-1),lvl+1])else:queue.append([node.left,lvl+1])ifnode.rightisNone:queue.append([Node(-1),lvl+1])else:queue.append([node.right,lvl+1])if__name__=="__main__":# Input Tree:# 1# / \# 2 3# / \# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)mirror(root)# Mirror Tree:# 1# / \# 3 2# / \# 5 4levelOrder(root)
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGFG{staticvoidmirror(Noderoot){if(root==null)return;Queue<Node>queue=newQueue<Node>();queue.Enqueue(root);// Traverse the tree, level by levelwhile(queue.Count>0){Nodecurr=queue.Dequeue();// Swap the left and right subtreeNodetemp=curr.left;curr.left=curr.right;curr.right=temp;// Push the left and right node to the queueif(curr.left!=null)queue.Enqueue(curr.left);if(curr.right!=null)queue.Enqueue(curr.right);}}staticintgetHeight(Noderoot,inth){if(root==null)returnh-1;returnMath.Max(getHeight(root.left,h+1),getHeight(root.right,h+1));}staticvoidlevelOrder(Noderoot){Queue<(Node,int)>queue=newQueue<(Node,int)>();queue.Enqueue((root,0));intlastLevel=0;// function to get the height of treeintheight=getHeight(root,0);// printing the level order of treewhile(queue.Count>0){var(node,lvl)=queue.Dequeue();if(lvl>lastLevel){Console.WriteLine();lastLevel=lvl;}// all levels are printedif(lvl>height)break;// printing null nodeConsole.Write((node.data==-1?"N":node.data.ToString())+" ");// null node has no childrenif(node.data==-1)continue;if(node.left==null)queue.Enqueue((newNode(-1),lvl+1));elsequeue.Enqueue((node.left,lvl+1));if(node.right==null)queue.Enqueue((newNode(-1),lvl+1));elsequeue.Enqueue((node.right,lvl+1));}}staticvoidMain(string[]args){// Input Tree:// 1// / \// 2 3// / \// 4 5Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);mirror(root);// Mirror Tree:// 1// / \// 3 2// / \// 5 4levelOrder(root);}}
JavaScript
// Custom Queue using linked list nodesclassQNode{constructor(data){this.data=data;this.next=null;}}classQueue{constructor(){this.front=null;this.rear=null;}isEmpty(){returnthis.front===null;}enqueue(x){letnewNode=newQNode(x);if(this.rear===null){this.front=this.rear=newNode;return;}this.rear.next=newNode;this.rear=newNode;}dequeue(){if(this.front===null)returnnull;lettemp=this.front;this.front=this.front.next;if(this.front===null)this.rear=null;returntemp.data;}}// Node StructureclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}functionmirror(root){if(root===null)return;letqueue=newQueue();queue.enqueue(root);// Traverse the tree, level by levelwhile(!queue.isEmpty()){letcurr=queue.dequeue();// Swap the left and right subtree[curr.left,curr.right]=[curr.right,curr.left];// Push the left and right node to the queueif(curr.left)queue.enqueue(curr.left);if(curr.right)queue.enqueue(curr.right);}}functiongetHeight(root,h){if(root===null)returnh-1;returnMath.max(getHeight(root.left,h+1),getHeight(root.right,h+1));}functionlevelOrder(root){letqueue=[];queue.push([root,0]);letlastLevel=0;// get the height of treeletheight=getHeight(root,0);// printing the level order of treewhile(queue.length>0){let[node,lvl]=queue.shift();if(lvl>lastLevel){console.log("");lastLevel=lvl;}// all levels are printedif(lvl>height)break;// printing null nodeprocess.stdout.write((node.data===-1?"N":node.data)+" ");// null node has no childrenif(node.data===-1)continue;if(node.left===null)queue.push([newNode(-1),lvl+1]);elsequeue.push([node.left,lvl+1]);if(node.right===null)queue.push([newNode(-1),lvl+1]);elsequeue.push([node.right,lvl+1]);}}// Driver Code// Input Tree:// 1// / \// 2 3// / \// 4 5letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);mirror(root);// Mirror Tree:// 1// / \// 3 2// / \// 5 4levelOrder(root);