Open In App

Iterative method to check if two trees are mirror of each other

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
16 Likes
Like
Report

Given two Binary Trees, the task is to check if two trees are mirrors of each other or not. For two trees ‘a’ and ‘b’ to be mirror images, the following three conditions must be true:  

  1. Their root node’s key must be same
  2. Left subtree of root of ‘a’ and right subtree root of ‘b’ are mirror.
  3. Right subtree of ‘a’ and left subtree of ‘b’ are mirror.

Example:

Input:

Two-Mirror-Trees-1

Output: True
Explanation: Both trees are mirror images of each other, so output is True.

Input:

Two-Mirror-Trees-2

Output: False
Explanation: Since both trees are not mirror images of each other, the output is False.


Approach:

The idea is to check if two binary trees are mirrors using two stacks to simulate the recursive process. Nodes from each tree are pushed onto the stacks in a manner that compares the left subtree of one tree with the right subtree of the other, and vice versa. By systematically comparing nodes from both trees while maintaining their mirrored structure in the stacks, the approach ensures that the trees are symmetric relative to their root.

Step-by-step implementation:

  • If both root1 and root2 are null, return true because two empty trees are mirrors of each other.
  • If one tree is null while the other isn't, return false, as they can't be mirrors.
  • Create two stacks, stk1 and stk2, to store nodes for simultaneous iterative traversal of both trees.
  • Pop nodes from both stacks, compare their data, and check if the current nodes have left and right children in a mirrored fashion (left of root1 with right of root2 and vice versa).
  • If the current node pairs have corresponding children, push them onto the stacks; otherwise, return false if the structure is not symmetric.
  • After traversal, if both stacks are empty, return true; otherwise, return false.

Below is implementation of above approach:

C++
// Iterative C++ program to check if two
// roots are mirror images of each other
#include <bits/stdc++.h>
using namespace std;

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

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

// Function to check if two roots are mirror 
// images iteratively
bool areMirrors(Node* root1, Node* root2) {

    // If both roots are empty, they are mirrors
    if (root1 == nullptr && root2 == nullptr)
        return true;

    // If only one root is empty, they are not 
    // mirrors
    if (root1 == nullptr || root2 == nullptr)
        return false;

    // Create two stacks for simultaneous 
    // traversal
    stack<Node*> stk1, stk2;
    
    // Push roots of both roots
    stk1.push(root1);
    stk2.push(root2);

    while (!stk1.empty() && !stk2.empty()) {

        // Pop from both stacks
        Node* curr1 = stk1.top(); stk1.pop();
        Node* curr2 = stk2.top(); stk2.pop();

        // Check if the data of the nodes is 
        // different
        if (curr1->data != curr2->data)
            return false;

        // Check for the next level of nodes in 
        // a mirror fashion
        if (curr1->left && curr2->right) {
            stk1.push(curr1->left);
            stk2.push(curr2->right);
        } 
        else if (curr1->left || curr2->right) {
            return false;
        }

        if (curr1->right && curr2->left) {
            stk1.push(curr1->right);
            stk2.push(curr2->left);
        } 
        else if (curr1->right || curr2->left) {
            return false;
        }
    }

    // If both stacks are empty, the roots are 
    // mirrors
    return stk1.empty() && stk2.empty();
}

int main() {

    // Representation of input binary tree 1
    //        1
    //       / \
    //      3   2
    //          / \
    //         5   4
    Node* root1 = new Node(1);
    root1->left = new Node(3);
    root1->right = new Node(2);
    root1->right->left = new Node(5);
    root1->right->right = new Node(4);

    // Representation of input binary tree 2 
    // (mirror)
    //        1
    //       / \
    //      2   3
    //     / \
    //    4   5
    Node* root2 = new Node(1);
    root2->left = new Node(2);
    root2->right = new Node(3);
    root2->left->left = new Node(4);
    root2->left->right = new Node(5);

    if (areMirrors(root1, root2))
        cout << "true\n";
    else
        cout << "false\n";

    return 0;
}
Java
// Iterative Java program to check if two
// roots are mirror images of each other
import java.util.Stack;

class Node {
    int data;
    Node left, right;

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

public class GfG {

    // Function to check if two roots are 
    // mirror images iteratively
    static boolean areMirrors(Node root1, Node root2) {

        // If both roots are empty, they are 
        // mirrors
        if (root1 == null && root2 == null) {
            return true;
        }

        // If only one root is empty, they are 
        // not mirrors
        if (root1 == null || root2 == null) {
            return false;
        }

        // Create two stacks for simultaneous 
        // traversal
        Stack<Node> stk1 = new Stack<>();
        Stack<Node> stk2 = new Stack<>();
        
        // Push roots of both roots
        stk1.push(root1);
        stk2.push(root2);

        while (!stk1.isEmpty() && !stk2.isEmpty()) {

            // Pop from both stacks
            Node curr1 = stk1.pop();
            Node curr2 = stk2.pop();

            // Check if the data of the nodes is 
            // different
            if (curr1.data != curr2.data) {
                return false;
            }

            // Check for the next level of nodes 
            // in a mirror fashion
            if (curr1.left != null 
                              && curr2.right != null) {
              
                stk1.push(curr1.left);
                stk2.push(curr2.right);
            } 
            else if (curr1.left != null 
                               || curr2.right != null) {
                return false;
            }

            if (curr1.right != null 
                              && curr2.left != null) {
              
                stk1.push(curr1.right);
                stk2.push(curr2.left);
            } 
            else if (curr1.right != null 
                          || curr2.left != null) {
              
                return false;
            }
        }

        // If both stacks are empty, the roots 
        // are mirrors
        return stk1.isEmpty() && stk2.isEmpty();
    }

    public static void main(String[] args) {

        // Representation of input binary tree 1
        //        1
        //       / \
        //      3   2
        //          / \
        //         5   4
        Node root1 = new Node(1);
        root1.left = new Node(3);
        root1.right = new Node(2);
        root1.right.left = new Node(5);
        root1.right.right = new Node(4);

        // Representation of input binary tree 2 
        // (mirror)
        //        1
        //       / \
        //      2   3
        //     / \
        //    4   5
        Node root2 = new Node(1);
        root2.left = new Node(2);
        root2.right = new Node(3);
        root2.left.left = new Node(4);
        root2.left.right = new Node(5);

        if (areMirrors(root1, root2)) {
            System.out.println("true");
        } 
        else {
            System.out.println("false");
        }
    }
}
Python
# Iterative Python program to check if two
# roots are mirror images of each other
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

def areMirrors(root1, root2):
  
    # If both roots are empty, they are mirrors
    if root1 is None and root2 is None:
        return True

    # If only one root is empty, they are not mirrors
    if root1 is None or root2 is None:
        return False

    # Initialize two stacks for simultaneous traversal
    stk1 = []
    stk2 = []
    
    # Push roots of both roots
    stk1.append(root1)
    stk2.append(root2)

    while stk1 and stk2:
      
        # Pop from both stacks
        curr1 = stk1.pop()
        curr2 = stk2.pop()

        # Check if the data of the nodes is different
        if curr1.data != curr2.data:
            return False

        # Check for the next level of nodes in a mirror 
        # fashion
        if curr1.left and curr2.right:
            stk1.append(curr1.left)
            stk2.append(curr2.right)
        elif curr1.left or curr2.right:
            return False

        if curr1.right and curr2.left:
            stk1.append(curr1.right)
            stk2.append(curr2.left)
        elif curr1.right or curr2.left:
            return False

    # If both stacks are empty, the roots are mirrors
    return not stk1 and not stk2

if __name__ == "__main__":
  
    # Representation of input binary tree 1
    #        1
    #       / \
    #      3   2
    #          / \
    #         5   4
    root1 = Node(1)
    root1.left = Node(3)
    root1.right = Node(2)
    root1.right.left = Node(5)
    root1.right.right = Node(4)

    # Representation of input binary tree 2 (mirror)
    #        1
    #       / \
    #      2   3
    #     / \
    #    4   5
    root2 = Node(1)
    root2.left = Node(2)
    root2.right = Node(3)
    root2.left.left = Node(4)
    root2.left.right = Node(5)

    if areMirrors(root1, root2):
        print("true")
    else:
        print("false")
C#
// Iterative C# program to check if two
// roots are mirror images of each other
using System;
using System.Collections.Generic;

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

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

class GfG {

    // Function to check if two roots are 
    // mirror images iteratively
    static bool AreMirrors(Node root1, Node root2) {

        // If both roots are empty, they are mirrors
        if (root1 == null && root2 == null)
            return true;

        // If only one root is empty, they are 
        // not mirrors
        if (root1 == null || root2 == null)
            return false;

        // Create two stacks for simultaneous 
        // traversal
        Stack<Node> stk1 = new Stack<Node>();
        Stack<Node> stk2 = new Stack<Node>();

        // Push roots of both roots
        stk1.Push(root1);
        stk2.Push(root2);

        while (stk1.Count > 0 && stk2.Count > 0) {

            // Pop from both stacks
            Node curr1 = stk1.Pop();
            Node curr2 = stk2.Pop();

            // Check if the data of the nodes is 
            // different
            if (curr1.data != curr2.data)
                return false;

            // Check for the next level of nodes 
            // in a mirror fashion
            if (curr1.left != null && curr2.right != null) {
                stk1.Push(curr1.left);
                stk2.Push(curr2.right);
            } 
            else if (curr1.left != null 
                                    || curr2.right != null) {
              
                return false;
            }

            if (curr1.right != null
                               && curr2.left != null) {
              
                stk1.Push(curr1.right);
                stk2.Push(curr2.left);
            } 
            else if (curr1.right != null 
                              || curr2.left != null) {
              
                return false;
            }
        }

        // If both stacks are empty, the roots 
        // are mirrors
        return stk1.Count == 0 && stk2.Count == 0;
    }

    static void Main() {

        // Representation of input binary tree 1
        //        1
        //       / \
        //      3   2
        //          / \
        //         5   4
        Node root1 = new Node(1);
        root1.left = new Node(3);
        root1.right = new Node(2);
        root1.right.left = new Node(5);
        root1.right.right = new Node(4);

        // Representation of input binary tree 2 
        // (mirror)
        //        1
        //       / \
        //      2   3
        //     / \
        //    4   5
        Node root2 = new Node(1);
        root2.left = new Node(2);
        root2.right = new Node(3);
        root2.left.left = new Node(4);
        root2.left.right = new Node(5);

        if (AreMirrors(root1, root2))
            Console.WriteLine("true");
        else
            Console.WriteLine("false");
    }
}
JavaScript
// Recursive JavaScript function to check if two
// roots are mirror images of each other
class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

// Function to check if two roots are mirror images
function areMirrors(root1, root2) {

    // If both roots are empty, they are mirrors
    if (root1 === null && root2 === null) {
        return true;
    }

    // If only one root is empty, they are not mirrors
    if (root1 === null || root2 === null) {
        return false;
    }

    // Create two stacks for simultaneous traversal
    const stk1 = [];
    const stk2 = [];

    // Push roots of both roots
    stk1.push(root1);
    stk2.push(root2);

    while (stk1.length > 0 && stk2.length > 0) {
    
        // Pop from both stacks
        const curr1 = stk1.pop();
        const curr2 = stk2.pop();

        // Check if the data of the nodes is different
        if (curr1.data !== curr2.data) {
            return false;
        }

        // Check for the next level of nodes 
        // in a mirror fashion
        if (curr1.left && curr2.right) {
            stk1.push(curr1.left);
            stk2.push(curr2.right);
        } 
        else if (curr1.left || curr2.right) {
            return false;
        }

        if (curr1.right && curr2.left) {
            stk1.push(curr1.right);
            stk2.push(curr2.left);
        } 
        else if (curr1.right || curr2.left) {
            return false;
        }
    }

    // If both stacks are empty, the roots are mirrors
    return stk1.length === 0 && stk2.length === 0;
}

// Representation of input binary tree 1
//        1
//       / \
//      3   2
//          / \
//         5   4
const root1 = new Node(1);
root1.left = new Node(3);
root1.right = new Node(2);
root1.right.left = new Node(5);
root1.right.right = new Node(4);

// Representation of input binary tree 2 (mirror)
//        1
//       / \
//      2   3
//     / \
//    4   5
const root2 = new Node(1);
root2.left = new Node(2);
root2.right = new Node(3);
root2.left.left = new Node(4);
root2.left.right = new Node(5);

if (areMirrors(root1, root2)) {
    console.log("true");
} 
else {
    console.log("false");
}

Output
true

Time Complexity: O(n), because we are visiting each node once, where n is the number of nodes in the trees.
Auxiliary Space: O(n)

Please refer to Check if two trees are Mirror to solve using recursion.


Iterative method to check if two trees are mirror of each other
Article Tags :

Explore