Invert Binary Tree - Change to Mirror Tree

Last Updated : 3 Aug, 2026

Given the root of a binary tree, convert the binary tree to its Mirror tree.

Note: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged.

Examples:

Input: root = [1, 2, 3, N, N, 4]
Output: [1, 3, 2, N, 4]
Explanation:

5

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

Input: root = [1, 2, 3, 4, 5]
Output: [1, 3, 2, N, N, 5, 4]
Explanation:

6

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

Try It Yourself
redirect icon

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.

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

class Node
{
  public:
    int data;
    Node *left, *right;

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

// Function to convert binary tree into its mirror tree.
void mirror(Node *root)
{
    // Base case
    if (root == nullptr)
        return;

    // Mirror left subtree
    mirror(root->left);

    // Mirror right subtree
    mirror(root->right);

    // Swap left and right child
    swap(root->left, root->right);
}

void printLevelOrder(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 nulls
    while (!ans.empty() && ans.back() == "N")
        ans.pop_back();

    cout << "[";
    for (int i = 0; i < ans.size(); i++)
    {
        cout << ans[i];
        if (i + 1 != ans.size())
            cout << ", ";
    }
    cout << "]";
}

int main()
{
    // root = [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);
    printLevelOrder(root);

    return 0;
}
Java
import java.util.*;

class Node {
    int data;
    Node left, right;

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

public class GFG {
    // Function to convert binary tree into its mirror tree.
    static void mirror(Node root)
    {
        // Base case
        if (root == null)
            return;

        // Mirror left subtree
        mirror(root.left);

        // Mirror right subtree
        mirror(root.right);

        // Swap left and right child
        Node temp = root.left;
        root.left = root.right;
        root.right = temp;
    }

    static void printLevelOrder(Node root)
    {
        if (root == null) {
            System.out.print("[]");
            return;
        }

        ArrayList<String> ans = new ArrayList<>();
        Queue<Node> q = new LinkedList<>();
        q.add(root);

        while (!q.isEmpty()) {
            Node curr = 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 nulls
        while (!ans.isEmpty()
               && ans.get(ans.size() - 1).equals("N"))
            ans.remove(ans.size() - 1);

        System.out.print("[");
        for (int i = 0; i < ans.size(); i++) {
            System.out.print(ans.get(i));
            if (i + 1 != ans.size())
                System.out.print(", ");
        }
        System.out.print("]");
    }

    public static void main(String[] args)
    {
        // root = [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);
        printLevelOrder(root);
    }
}
Python
from collections import deque

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

# Function to convert binary tree into its mirror tree.
def mirror(root):
    # Base case
    if root is None:
        return

    # Mirror left subtree
    mirror(root.left)

    # Mirror right subtree
    mirror(root.right)

    # Swap left and right child
    root.left, root.right = root.right, root.left


def print_level_order(root):
    if root is None:
        print('[]')
        return

    ans = []
    q = deque([root])

    while q:
        curr = q.popleft()

        if curr:
            ans.append(str(curr.data))
            q.append(curr.left)
            q.append(curr.right)
        else:
            ans.append('N')

    # Remove trailing nulls
    while ans and ans[-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#
using System;
using System.Collections.Generic;

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

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

class GFG {
    // Function to convert binary tree into its mirror tree.
    static void mirror(Node root)
    {
        // Base case
        if (root == null)
            return;

        // Mirror left subtree
        mirror(root.left);

        // Mirror right subtree
        mirror(root.right);

        // Swap left and right child
        Node temp = root.left;
        root.left = root.right;
        root.right = temp;
    }

    static void PrintLevelOrder(Node root)
    {
        if (root == null) {
            Console.Write("[]");
            return;
        }

        List<string> ans = new List<string>();
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);

        while (q.Count > 0) {
            Node curr = q.Dequeue();

            if (curr != null) {
                ans.Add(curr.data.ToString());
                q.Enqueue(curr.left);
                q.Enqueue(curr.right);
            }
            else {
                ans.Add("N");
            }
        }

        // Remove trailing nulls
        while (ans.Count > 0 && ans[ans.Count - 1] == "N")
            ans.RemoveAt(ans.Count - 1);

        Console.Write("[");
        for (int i = 0; i < ans.Count; i++) {
            Console.Write(ans[i]);
            if (i + 1 != ans.Count)
                Console.Write(", ");
        }
        Console.Write("]");
    }

    static void Main(string[] args)
    {
        // root = [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);
        PrintLevelOrder(root);
    }
}
JavaScript
class Node {
    constructor(x)
    {
        this.data = x;
        this.left = this.right = null;
    }
}

// Function to convert binary tree into its mirror tree.
function mirror(root)
{
    // Base case
    if (root === null)
        return;

    // Mirror left subtree
    mirror(root.left);

    // Mirror right subtree
    mirror(root.right);

    // Swap left and right child
    let temp = root.left;
    root.left = root.right;
    root.right = temp;
}

function printLevelOrder(root)
{
    if (root === null) {
        console.log("[]");
        return;
    }

    let ans = [];
    let q = [ root ];

    while (q.length > 0) {
        let curr = q.shift();

        if (curr !== null) {
            ans.push(curr.data.toString());
            q.push(curr.left);
            q.push(curr.right);
        }
        else {
            ans.push("N");
        }
    }

    // Remove trailing nulls
    while (ans.length > 0 && ans[ans.length - 1] === "N")
        ans.pop();

    console.log("[" + ans.join(", ") + "]");
}

// Driver Code
// root = [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);
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].
6
C++
#include <iostream>
#include <queue>
using namespace std;

class Node
{
  public:
    int data;
    Node *left, *right;

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

// Function to convert binary tree into its mirror tree.
void mirror(Node *root)
{

    // If tree is empty
    if (root == nullptr)
        return;

    queue<Node *> q;
    q.push(root);

    while (!q.empty())
    {

        // Get the front node
        Node *curr = q.front();
        q.pop();

        // Swap left and right child
        swap(curr->left, curr->right);

        // Push left child
        if (curr->left)
            q.push(curr->left);

        // Push right child
        if (curr->right)
            q.push(curr->right);
    }
}

void printLevelOrder(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 nulls
    while (!ans.empty() && ans.back() == "N")
        ans.pop_back();

    cout << "[";
    for (int i = 0; i < ans.size(); i++)
    {
        cout << ans[i];
        if (i + 1 != ans.size())
            cout << ", ";
    }
    cout << "]";
}

int main()
{
    // root = [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);
    printLevelOrder(root);

    return 0;
}
Java
import java.util.*;

// Structure of a binary tree node
class Node {
    int data;
    Node left, right;

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

public class GFG {

    // Function to convert binary tree into its mirror tree.
    static void mirror(Node root)
    {

        // If tree is empty
        if (root == null)
            return;

        Queue<Node> q = new LinkedList<>();
        q.offer(root);

        while (!q.isEmpty()) {

            // Get the front node
            Node curr = q.poll();

            // Swap left and right child
            Node temp = curr.left;
            curr.left = curr.right;
            curr.right = temp;

            // Push left child
            if (curr.left != null)
                q.offer(curr.left);

            // Push right child
            if (curr.right != null)
                q.offer(curr.right);
        }
    }

    static void printLevelOrder(Node root)
    {
        if (root == null) {
            System.out.print("[]");
            return;
        }

        ArrayList<String> ans = new ArrayList<>();
        Queue<Node> q = new LinkedList<>();
        q.offer(root);

        while (!q.isEmpty()) {
            Node curr = 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 nulls
        while (!ans.isEmpty()
               && ans.get(ans.size() - 1).equals("N"))
            ans.remove(ans.size() - 1);

        System.out.print("[");
        for (int i = 0; i < ans.size(); i++) {
            System.out.print(ans.get(i));
            if (i + 1 != ans.size())
                System.out.print(", ");
        }
        System.out.print("]");
    }

    public static void main(String[] args)
    {

        // root = [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);
        printLevelOrder(root);
    }
}
Python
from collections import deque


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

# Function to convert binary tree into its mirror tree.


def mirror(root):

    # If tree is empty
    if root is None:
        return

    q = deque()
    q.append(root)

    while len(q) > 0:

        # Get the front node
        curr = q.popleft()

        # Swap left and right child
        curr.left, curr.right = curr.right, curr.left

        # Push left child
        if curr.left is not None:
            q.append(curr.left)

        # Push right child
        if curr.right is not None:
            q.append(curr.right)


def print_level_order(root):
    if root is None:
        print("[]")
        return

    ans = []
    q = deque()
    q.append(root)

    while len(q) > 0:
        curr = q.popleft()

        if curr is not None:
            ans.append(str(curr.data))
            q.append(curr.left)
            q.append(curr.right)
        else:
            ans.append("N")

    # Remove trailing nulls
    while len(ans) > 0 and ans[-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#
using System;
using System.Collections.Generic;

// Structure of a binary tree node
class Node {
    public int data;
    public Node left, right;

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

class GFG {
    // Function to convert binary tree into its mirror tree.
    static void mirror(Node root)
    {
        // If tree is empty
        if (root == null)
            return;

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

        while (q.Count > 0) {
            // Get the front node
            Node curr = q.Dequeue();

            // Swap left and right child
            Node temp = curr.left;
            curr.left = curr.right;
            curr.right = temp;

            // Push left child
            if (curr.left != null)
                q.Enqueue(curr.left);

            // Push right child
            if (curr.right != null)
                q.Enqueue(curr.right);
        }
    }

    static void PrintLevelOrder(Node root)
    {
        if (root == null) {
            Console.Write("[]");
            return;
        }

        List<string> ans = new List<string>();
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);

        while (q.Count > 0) {
            Node curr = q.Dequeue();

            if (curr != null) {
                ans.Add(curr.data.ToString());
                q.Enqueue(curr.left);
                q.Enqueue(curr.right);
            }
            else {
                ans.Add("N");
            }
        }

        // Remove trailing nulls
        while (ans.Count > 0 && ans[ans.Count - 1] == "N")
            ans.RemoveAt(ans.Count - 1);

        Console.Write("[");
        for (int i = 0; i < ans.Count; i++) {
            Console.Write(ans[i]);
            if (i + 1 != ans.Count)
                Console.Write(", ");
        }
        Console.Write("]");
    }

    static void Main(string[] args)
    {
        // root = [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);
        PrintLevelOrder(root);
    }
}
JavaScript
// Structure of a binary tree node
function Node(x)
{
    this.data = x;
    this.left = null;
    this.right = null;
}

// Function to convert binary tree into its mirror tree.
function mirror(root)
{

    // If tree is empty
    if (root === null)
        return;

    let q = [];
    q.push(root);

    while (q.length > 0) {

        // Get the front node
        let curr = q.shift();

        // Swap left and right child
        let temp = curr.left;
        curr.left = curr.right;
        curr.right = temp;

        // Push left child
        if (curr.left)
            q.push(curr.left);

        // Push right child
        if (curr.right)
            q.push(curr.right);
    }
}

function printLevelOrder(root)
{
    if (!root) {
        console.log("[]");
        return;
    }

    let ans = [];
    let q = [];
    q.push(root);

    while (q.length > 0) {
        let curr = q.shift();

        if (curr) {
            ans.push(curr.data.toString());
            q.push(curr.left);
            q.push(curr.right);
        }
        else {
            ans.push("N");
        }
    }

    // Remove trailing nulls
    while (ans.length > 0 && ans[ans.length - 1] === "N")
        ans.pop();

    console.log("[" + ans.join(", ") + "]");
}

// Driver Code
// root = [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);
printLevelOrder(root);

Output
[1, 3, 2, N, N, 5, 4]
Comment