Invert Binary Tree - Change to Mirror Tree

Last Updated : 6 Oct, 2025

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:

420046772

Output:

420046773

Explanation: In the inverted tree, every non-leaf node has its left and right child interchanged.

420046692


Input:

420046775

Output:

420046776

Explanation: In the inverted tree, every non-leaf node has its left and right child interchanged.

420046774
Try it on GfG Practice
redirect icon

[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>
using namespace std;

// Node Structure
class Node {
public:
    int data;
    Node *left, *right;
    Node(int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// function to return the root of inverted tree
void mirror(Node* root) {
    if (root == nullptr)
        return ;
    
    // Invert the left and right subtree
    mirror(root->left);
    mirror(root->right);
  
	swap(root->left, root->right);
}

int getHeight(Node* root, int h) {
    if (root == nullptr) return h - 1;
    return max(getHeight(root->left, h + 1), getHeight(root->right, h + 1));
}

void levelOrder(Node* root) {
    queue<pair<Node*, int>> q;
    q.push({root, 0});

    int lastLevel = 0;

    // function to get the height of tree
    int height = getHeight(root, 0);

    // printing the level order of tree
    while (!q.empty()) {
        auto top = q.front(); q.pop();
        Node* node = top.first;
        int lvl = top.second;

        if (lvl > lastLevel) {
            cout << "\n";
            lastLevel = lvl;
        }

        // all levels are printed
        if (lvl > height) break;

        
        if (node->data != -1) cout << node->data << " ";
        
        // printing null node
        else cout << "N ";

        // null node has no children
        if (node->data == -1) continue;

        if (node->left == nullptr) q.push({new Node(-1), lvl + 1});
        else q.push({node->left, lvl + 1});

        if (node->right == nullptr) q.push({new Node(-1), lvl + 1});
        else q.push({node->right, lvl + 1});
    }
}

int main() {

    // Input Tree:
    //       1
    //      / \
    //     2   3
    //    / \
    //   4   5
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);

	mirror(root);
  
    // Mirror Tree:
    //       1
    //      / \
    //     3   2
    //        / \
    //       5   4
    levelOrder(root);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Node Structure
struct Node {
    int data;
    struct Node *left, *right;
};

struct Node* createNode(int x) {
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
    node->data = x;
    node->left = NULL;
    node->right = NULL;
    return node;
}

// Queue implementation for struct Node*
#define MAX_SIZE 100

struct Queue {
    struct Node* items[MAX_SIZE];
    int front, rear;
};

void initQueue(struct Queue* q) {
    q->front = 0;
    q->rear = 0;
}

int isEmpty(struct Queue* q) {
    return q->front == q->rear;
}

void enqueue(struct Queue* q, struct Node* node) {
    if (q->rear < MAX_SIZE) {
        q->items[q->rear++] = node;
    }
}

// Dequeue an item
struct Node* dequeue(struct Queue* q) {
    if (!isEmpty(q)) {
        return q->items[q->front++];
    }
    return NULL;
}



void swap(struct Node** a, struct Node** b) {
    struct Node* temp = *a;
    *a = *b;
    *b = temp;
}

void mirror(struct Node* root) {
    if (root == NULL)
        return;
        
    // Invert the left and right subtree
    mirror(root->left);
    mirror(root->right);
    
    swap(&(root->left), &(root->right));
}

void levelOrder(struct Node* root) {
    if (root == NULL) {
        printf("N ");
        return;
    }

    struct Queue qq;
    initQueue(&qq);
    enqueue(&qq, root);

    while (!isEmpty(&qq)) {
        struct Node* curr = dequeue(&qq);

        if (curr == NULL) {
            printf("N ");
            continue;
        }
        printf("%d ", curr->data);
        enqueue(&qq, curr->left);
        enqueue(&qq, curr->right);
    }
}

int main() {

    // Input Tree:
    //       1
    //      / \
    //     2   3
    //    / \
    //   4   5
    struct Node* 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   4
    levelOrder(root);

    return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;
import java.util.List;
import java.util.ArrayList;

// Node Structure
class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GFG {

    // Function to return the root of inverted tree
    static void mirror(Node root) {
        if (root == null)
            return ;

        // Invert the left and right subtree
		mirror(root.left);
		mirror(root.right);

        Node temp = root.left;
        root.left = root.right;
        root.right = temp;
    }
    
    static int getHeight( Node root, int h ) {
        if( root == null ) return h-1;
        
        return Math.max(getHeight(root.left, h+1), getHeight(root.right, h+1));
    }
    
    static void levelOrder(Node root) {
        Queue<List<Object>> queue = new LinkedList<>();
        queue.offer(List.of(root, 0));
        
        int lastLevel = 0;
        
        // function to get the height of tree
        int height = getHeight(root, 0);
        
        // printing the level order of tree
        while( !queue.isEmpty()) {
            List<Object> top = queue.poll();
            
            Node node = (Node) top.get(0);
            int lvl = (int) top.get(1);
            
            if( lvl > lastLevel ) {
                System.out.println();
                lastLevel = lvl;
            }
            
            // all levels are printed
            if( lvl > height ) break;
            
            // printing null node
            System.out.print((node.data == -1 ? "N" : node.data) + " ");
            
            // null node has no children
            if( node.data == -1 ) continue;
            
            if( node.left == null ) queue.offer(List.of(new Node(-1), lvl+1));
            else queue.offer(List.of(node.left, lvl+1));
            
            if( node.right == null ) queue.offer(List.of(new Node(-1), lvl+1));
            else queue.offer(List.of(node.right, lvl+1));
        }
    }

    public static void main(String[] args) {
        // Input Tree:
        //       1
        //      / \
        //     2   3
        //    / \
        //   4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);

        mirror(root);

        // Mirror Tree:
        //       1
        //      / \
        //     3   2
        //        / \
        //       5   4
        levelOrder(root);
    }
}
Python
from collections import deque

# Node Structure
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function to return the root of inverted tree
def mirror(root):
    if root is None:
        return
    
    # Invert the left and right subtree
    mirror(root.left)
    mirror(root.right)
    
    root.left, root.right = root.right, root.left;

def getHeight(root, h):
    if root is None:
        return h - 1
    return max(getHeight(root.left, h + 1), getHeight(root.right, h + 1))


def levelOrder(root):
    queue = deque([[root, 0]])
    lastLevel = 0

    # function to get the height of tree
    height = getHeight(root, 0)

    # printing the level order of tree
    while queue:
        node, lvl = queue.popleft()

        if lvl > lastLevel:
            print()
            lastLevel = lvl

        # all levels are printed
        if lvl > height:
            break

        # printing null node
        print("N" if node.data == -1 else node.data, end=" ")

        # null node has no children
        if node.data == -1:
            continue

        if node.left is None:
            queue.append([Node(-1), lvl + 1])
        else:
            queue.append([node.left, lvl + 1])

        if node.right is None:
            queue.append([Node(-1), lvl + 1])
        else:
            queue.append([node.right, lvl + 1])
            

if __name__ == "__main__":
    # Input Tree:
    #       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)

    # Mirror Tree:
    #       1
    #      / \
    #     3   2
    #        / \
    #       5   4
    levelOrder(root)
C#
using System;
using System.Collections.Generic;

// Node Structure
class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GFG {

    static void mirror(Node root) {
        if (root == null)
            return;

        // Invert the left and right subtree
        mirror(root.left);
        mirror(root.right);

        Node temp = root.left;
        root.left = root.right;
        root.right = temp;
    }
    
    static int getHeight(Node root, int h) {
        if (root == null) return h - 1;
        return Math.Max(getHeight(root.left, h + 1), getHeight(root.right, h + 1));
    }

    static void levelOrder(Node root) {
        Queue<(Node, int)> queue = new Queue<(Node, int)>();
        queue.Enqueue((root, 0));

        int lastLevel = 0;

        // function to get the height of tree
        int height = getHeight(root, 0);

        // printing the level order of tree
        while (queue.Count > 0) {
            var (node, lvl) = queue.Dequeue();

            if (lvl > lastLevel) {
                Console.WriteLine();
                lastLevel = lvl;
            }

            // all levels are printed
            if (lvl > height) break;

            // printing null node
            Console.Write((node.data == -1 ? "N" : node.data.ToString()) + " ");

            // null node has no children
            if (node.data == -1) continue;

            if (node.left == null) queue.Enqueue((new Node(-1), lvl + 1));
            else queue.Enqueue((node.left, lvl + 1));

            if (node.right == null) queue.Enqueue((new Node(-1), lvl + 1));
            else queue.Enqueue((node.right, lvl + 1));
        }
    }

    static void Main() {
        // Input Tree:
        //       1
        //      / \
        //     2   3
        //    / \
        //   4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);

        mirror(root);

        // Mirror Tree:
        //       1
        //      / \
        //     3   2
        //        / \
        //       5   4
        levelOrder(root);
    }
}
JavaScript
// Queue node
class QNode {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

class Queue {
    constructor() {
        this.front = null;
        this.rear = null;
    }

    isEmpty() {
        return this.front === null;
    }

    enqueue(x) {
        let newNode = new QNode(x);
        if (this.rear === null) {
            this.front = this.rear = newNode;
            return;
        }
        this.rear.next = newNode;
        this.rear = newNode;
    }

    dequeue() {
        if (this.front === null)
            return null;

        let temp = this.front;
        this.front = this.front.next;

        if (this.front === null)
            this.rear = null;

        return temp.data;
    }
}

// Node Structure
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function to return the root of inverted tree
function mirror(root) {
    if (root === null)
        return;

    // Invert the left and right subtree
    mirror(root.left);
    mirror(root.right);

    let temp = root.left;
    root.left = root.right;
    root.right = temp;
}

function getHeight(root, h) {
    if (root === null) return h - 1;
    return Math.max(getHeight(root.left, h + 1), getHeight(root.right, h + 1));
}

function levelOrder(root) {
    let queue = [];
    queue.push([root, 0]);

    let lastLevel = 0;

    // get the height of tree
    let height = getHeight(root, 0);

    // printing the level order of tree
    while (queue.length > 0) {
        let [node, lvl] = queue.shift();

        if (lvl > lastLevel) {
            console.log("");
            lastLevel = lvl;
        }

        // all levels are printed
        if (lvl > height) break;

        // printing null node
        process.stdout.write((node.data === -1 ? "N" : node.data) + " ");

        // null node has no children
        if (node.data === -1) continue;

        if (node.left === null) queue.push([new Node(-1), lvl + 1]);
        else queue.push([node.left, lvl + 1]);

        if (node.right === null) queue.push([new Node(-1), lvl + 1]);
        else queue.push([node.right, lvl + 1]);
    }
}


// Driver Code

// Input Tree:
//       1
//      / \
//     2   3
//    / \
//   4   5
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);

mirror(root);

// Mirror Tree:
//       1
//      / \
//     3   2
//        / \
//       5   4
levelOrder(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> 
using namespace std;

// Node Structure
class Node {
public:
    int data;
    Node *left, *right;
    Node(int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

void mirror(Node* root) {
    if (root == nullptr)
        return ;
    
    queue<Node*> q;
    q.push(root);
    
    // Traverse the tree, level by level
    while(!q.empty()) {
        Node* curr = q.front();
        q.pop();
      
        // Swap the left and right subtree
        swap(curr->left, curr->right);
      
        // Push the left and right node to the queue
        if(curr->left != nullptr)
          q.push(curr->left);
        if(curr->right != nullptr)
          q.push(curr->right);
    }
}

int getHeight(Node* root, int h) {
    if (root == nullptr) return h - 1;
    return max(getHeight(root->left, h + 1), getHeight(root->right, h + 1));
}

void levelOrder(Node* root) {
    queue<pair<Node*, int>> q;
    q.push({root, 0});

    int lastLevel = 0;

    // function to get the height of tree
    int height = getHeight(root, 0);

    // printing the level order of tree
    while (!q.empty()) {
        auto top = q.front(); q.pop();
        Node* node = top.first;
        int lvl = top.second;

        if (lvl > lastLevel) {
            cout << "\n";
            lastLevel = lvl;
        }

        // all levels are printed
        if (lvl > height) break;

        
        if (node->data != -1) cout << node->data << " ";
        
        // printing null node
        else cout << "N ";

        // null node has no children
        if (node->data == -1) continue;

        if (node->left == nullptr) q.push({new Node(-1), lvl + 1});
        else q.push({node->left, lvl + 1});

        if (node->right == nullptr) q.push({new Node(-1), lvl + 1});
        else q.push({node->right, lvl + 1});
    }
}

int main() {

    // Input Tree:
    //       1
    //      / \
    //     2   3
    //    / \
    //   4   5
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);

    mirror(root);
  
    // Mirror Tree:
    //       1
    //      / \
    //     3   2
    //        / \
    //       5   4
    levelOrder(root);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

// Node structure
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// helper struct to store {node, start, end}
struct Data {
    struct Node* node;
    int start;
    int end;
};

// queue element for Node + level
struct QueueNode {
    struct Node* node;
    int level;
    struct QueueNode* next;
};

// queue for Data
struct DataQueueNode {
    struct Data data;
    struct DataQueueNode* next;
};

// -------- Queue for levelOrder --------
struct QueueNode* createQueueNode(struct Node* node, int level) {
    struct QueueNode* temp = (struct QueueNode*)malloc(sizeof(struct QueueNode));
    temp->node = node;
    temp->level = level;
    temp->next = NULL;
    return temp;
}

void enqueue(struct QueueNode** front, struct QueueNode** rear, struct Node* node, int level) {
    struct QueueNode* temp = createQueueNode(node, level);
    if (*rear == NULL) {
        *front = *rear = temp;
        return;
    }
    (*rear)->next = temp;
    *rear = temp;
}

struct QueueNode* dequeue(struct QueueNode** front, struct QueueNode** rear) {
    if (*front == NULL) return NULL;
    struct QueueNode* temp = *front;
    *front = (*front)->next;
    if (*front == NULL) *rear = NULL;
    return temp;
}

int isQueueEmpty(struct QueueNode* front) {
    return front == NULL;
}

// -------- Queue for Data --------
struct DataQueueNode* createDataNode(struct Data d) {
    struct DataQueueNode* temp = (struct DataQueueNode*)malloc(sizeof(struct DataQueueNode));
    temp->data = d;
    temp->next = NULL;
    return temp;
}

void enqueueData(struct DataQueueNode** front, struct DataQueueNode** rear, struct Data d) {
    struct DataQueueNode* temp = createDataNode(d);
    if (*rear == NULL) {
        *front = *rear = temp;
        return;
    }
    (*rear)->next = temp;
    *rear = temp;
}

struct Data dequeueData(struct DataQueueNode** front, struct DataQueueNode** rear) {
    struct DataQueueNode* temp = *front;
    struct Data d = temp->data;
    *front = (*front)->next;
    if (*front == NULL) *rear = NULL;
    free(temp);
    return d;
}

int isDataQueueEmpty(struct DataQueueNode* front) {
    return front == NULL;
}

// -------- Node and Tree functions --------
struct Node* newNode(int data) {
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return node;
}

int getHeight(struct Node* root, int h) {
    if (root == NULL) return h - 1;
    int left = getHeight(root->left, h + 1);
    int right = getHeight(root->right, h + 1);
    return (left > right) ? left : right;
}

void levelOrder(struct Node* root) {
    struct QueueNode* front = NULL;
    struct QueueNode* rear = NULL;

    enqueue(&front, &rear, root, 0);

    int lastLevel = 0;

    // function to get the height of tree
    int height = getHeight(root, 0);

    // printing the level order of tree
    while (!isQueueEmpty(front)) {
        struct QueueNode* top = dequeue(&front, &rear);

        struct Node* node = top->node;
        int lvl = top->level;
        free(top);

        if (lvl > lastLevel) {
            printf("\n");
            lastLevel = lvl;
        }

        // all levels are printed
        if (lvl > height) break;

        if (node->data != -1) printf("%d ", node->data);
        
        // printing null node
        else printf("%s ", "N");

        // null node has no children
        if (node->data == -1) continue;

        if (node->left == NULL)
            enqueue(&front, &rear, newNode(-1), lvl + 1);
        else
            enqueue(&front, &rear, node->left, lvl + 1);

        if (node->right == NULL)
            enqueue(&front, &rear, newNode(-1), lvl + 1);
        else
            enqueue(&front, &rear, node->right, lvl + 1);
    }
}

struct Node* sortedArrayToBST(int arr[], int n) {
    if (n == 0) return NULL;

    // create the root node.
    int mid = (n - 1) / 2;
    struct Node* root = newNode(arr[mid]);

    struct DataQueueNode* front = NULL;
    struct DataQueueNode* rear = NULL;

    struct Data d = {root, 0, n - 1};
    enqueueData(&front, &rear, d);

    while (!isDataQueueEmpty(front)) {
        struct Data currData = dequeueData(&front, &rear);

        struct Node* curr = currData.node;
        int st = currData.start, en = currData.end;
        mid = (st + en) / 2;

        // if left subtree exists
        if (st < mid) {
            int leftVal = (st + mid - 1) / 2;
            struct Node* left = newNode(arr[leftVal]);
            curr->left = left;
            struct Data newD = {left, st, mid - 1};
            enqueueData(&front, &rear, newD);
        }

        // if right subtree exists
        if (en > mid) {
            int rightVal = (mid + 1 + en) / 2;
            struct Node* right = newNode(arr[rightVal]);
            curr->right = right;
            struct Data newD = {right, mid + 1, en};
            enqueueData(&front, &rear, newD);
        }
    }

    return root;
}

int main() {
    int arr[] = {1, 5, 9, 14, 23, 27};
    int n = sizeof(arr) / sizeof(arr[0]);

    struct Node* root = sortedArrayToBST(arr, n);
    levelOrder(root);

    return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;
import java.util.List;
import java.util.ArrayList;

// Node Structure
class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GFG {

    static void mirror(Node root) {
        if (root == null)
            return;

        Queue<Node> queue = new LinkedList<>();
        queue.add(root);

        // Traverse the tree, level by level
        while (!queue.isEmpty()) {
            Node curr = queue.poll();

            // Swap the left and right subtree
            Node temp = curr.left;
            curr.left = curr.right;
            curr.right = temp;

            // Push the left and right node to the queue
            if (curr.left != null)
                queue.add(curr.left);
            if (curr.right != null)
                queue.add(curr.right);
        }
    }
    
    static int getHeight( Node root, int h ) {
        if( root == null ) return h-1;
        
        return Math.max(getHeight(root.left, h+1), getHeight(root.right, h+1));
    }
    
    static void levelOrder(Node root) {
        Queue<List<Object>> queue = new LinkedList<>();
        queue.offer(List.of(root, 0));
        
        int lastLevel = 0;
        
        // function to get the height of tree
        int height = getHeight(root, 0);
        
        // printing the level order of tree
        while( !queue.isEmpty()) {
            List<Object> top = queue.poll();
            
            Node node = (Node) top.get(0);
            int lvl = (int) top.get(1);
            
            if( lvl > lastLevel ) {
                System.out.println();
                lastLevel = lvl;
            }
            
            // all levels are printed
            if( lvl > height ) break;
            
            // printing null node
            System.out.print((node.data == -1 ? "N" : node.data) + " ");
            
            // null node has no children
            if( node.data == -1 ) continue;
            
            if( node.left == null ) queue.offer(List.of(new Node(-1), lvl+1));
            else queue.offer(List.of(node.left, lvl+1));
            
            if( node.right == null ) queue.offer(List.of(new Node(-1), lvl+1));
            else queue.offer(List.of(node.right, lvl+1));
        }
    }

    public static void main(String[] args) {
        // Input Tree:
        //       1
        //      / \
        //     2   3
        //    / \
        //   4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);

        mirror(root);

        // Mirror Tree:
        //       1
        //      / \
        //     3   2
        //        / \
        //       5   4
        levelOrder(root);
    }
}
Python
from collections import deque

# Node Structure
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None


def mirror(root):
    if root is None:
        return

    queue = deque([root])

    # Traverse the tree, level by level
    while queue:
        curr = queue.popleft()

        # Swap the left and right subtree
        curr.left, curr.right = curr.right, curr.left

        # Push the left and right node to the queue
        if curr.left:
            queue.append(curr.left)
        if curr.right:
            queue.append(curr.right)


def getHeight(root, h):
    if root is None:
        return h - 1
    return max(getHeight(root.left, h + 1), getHeight(root.right, h + 1))


def levelOrder(root):
    queue = deque([[root, 0]])
    lastLevel = 0

    # function to get the height of tree
    height = getHeight(root, 0)

    # printing the level order of tree
    while queue:
        node, lvl = queue.popleft()

        if lvl > lastLevel:
            print()
            lastLevel = lvl

        # all levels are printed
        if lvl > height:
            break

        # printing null node
        print("N" if node.data == -1 else node.data, end=" ")

        # null node has no children
        if node.data == -1:
            continue

        if node.left is None:
            queue.append([Node(-1), lvl + 1])
        else:
            queue.append([node.left, lvl + 1])

        if node.right is None:
            queue.append([Node(-1), lvl + 1])
        else:
            queue.append([node.right, lvl + 1])

if __name__ == "__main__":
    # Input Tree:
    #       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)

    # Mirror Tree:
    #       1
    #      / \
    #     3   2
    #        / \
    #       5   4
    levelOrder(root)
C#
using System;
using System.Collections.Generic;

// Node Structure
class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GFG {
  
    static void mirror(Node root) {
        if (root == null)
            return;

        Queue<Node> queue = new Queue<Node>();
        queue.Enqueue(root);

        // Traverse the tree, level by level
        while (queue.Count > 0) {
            Node curr = queue.Dequeue();

            // Swap the left and right subtree
            Node temp = curr.left;
            curr.left = curr.right;
            curr.right = temp;

            // Push the left and right node to the queue
            if (curr.left != null)
                queue.Enqueue(curr.left);
            if (curr.right != null)
                queue.Enqueue(curr.right);
        }
    }

    
    static int getHeight(Node root, int h) {
        if (root == null) return h - 1;
        return Math.Max(getHeight(root.left, h + 1), getHeight(root.right, h + 1));
    }
    
    static void levelOrder(Node root) {
        Queue<(Node, int)> queue = new Queue<(Node, int)>();
        queue.Enqueue((root, 0));

        int lastLevel = 0;

        // function to get the height of tree
        int height = getHeight(root, 0);

        // printing the level order of tree
        while (queue.Count > 0) {
            var (node, lvl) = queue.Dequeue();

            if (lvl > lastLevel) {
                Console.WriteLine();
                lastLevel = lvl;
            }

            // all levels are printed
            if (lvl > height) break;

            // printing null node
            Console.Write((node.data == -1 ? "N" : node.data.ToString()) + " ");

            // null node has no children
            if (node.data == -1) continue;

            if (node.left == null) queue.Enqueue((new Node(-1), lvl + 1));
            else queue.Enqueue((node.left, lvl + 1));

            if (node.right == null) queue.Enqueue((new Node(-1), lvl + 1));
            else queue.Enqueue((node.right, lvl + 1));
        }
    }


    static void Main(string[] args) {
        // Input Tree:
        //       1
        //      / \
        //     2   3
        //    / \
        //   4   5
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);

        mirror(root);

        // Mirror Tree:
        //       1
        //      / \
        //     3   2
        //        / \
        //       5   4
        levelOrder(root);
    }
}
JavaScript
// Custom Queue using linked list nodes
class QNode {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

class Queue {
    constructor() {
        this.front = null;
        this.rear = null;
    }

    isEmpty() {
        return this.front === null;
    }

    enqueue(x) {
        let newNode = new QNode(x);
        if (this.rear === null) {
            this.front = this.rear = newNode;
            return;
        }
        this.rear.next = newNode;
        this.rear = newNode;
    }

    dequeue() {
        if (this.front === null)
            return null;

        let temp = this.front;
        this.front = this.front.next;

        if (this.front === null)
            this.rear = null;

        return temp.data;
    }
}

// Node Structure
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

function mirror(root) {
    if (root === null)
        return;

    let queue = new Queue();
    queue.enqueue(root);

    // Traverse the tree, level by level
    while (!queue.isEmpty()) {
        let curr = queue.dequeue();

        // Swap the left and right subtree
        [curr.left, curr.right] = [curr.right, curr.left];

        // Push the left and right node to the queue
        if (curr.left)
            queue.enqueue(curr.left);
        if (curr.right)
            queue.enqueue(curr.right);
    }
}
function getHeight(root, h) {
    if (root === null) return h - 1;
    return Math.max(getHeight(root.left, h + 1), getHeight(root.right, h + 1));
}

function levelOrder(root) {
    let queue = [];
    queue.push([root, 0]);

    let lastLevel = 0;

    // get the height of tree
    let height = getHeight(root, 0);

    // printing the level order of tree
    while (queue.length > 0) {
        let [node, lvl] = queue.shift();

        if (lvl > lastLevel) {
            console.log("");
            lastLevel = lvl;
        }

        // all levels are printed
        if (lvl > height) break;

        // printing null node
        process.stdout.write((node.data === -1 ? "N" : node.data) + " ");

        // null node has no children
        if (node.data === -1) continue;

        if (node.left === null) queue.push([new Node(-1), lvl + 1]);
        else queue.push([node.left, lvl + 1]);

        if (node.right === null) queue.push([new Node(-1), lvl + 1]);
        else queue.push([node.right, lvl + 1]);
    }
}

// Driver Code
// Input Tree:
//       1
//      / \
//     2   3
//    / \
//   4   5
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);

mirror(root);

// Mirror Tree:
//       1
//      / \
//     3   2
//        / \
//       5   4
levelOrder(root);

Output
1 
3 2 
N N 5 4 
Comment