Check if two trees are mirror of each other using level order traversal

Given two binary trees, the task is to check whether the two binary trees is a mirror of each other or not.
Mirror of a Binary Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged.
Â
Trees in the above figure are mirrors of each other.
A recursive solution and an iterative method using inorder traversal to check whether the two binary trees is a mirror of each other or not have been already discussed. In this post a solution using level order traversal has been discussed.
The idea is to use a queue in which two nodes of both the trees which needs to be checked for equality are present together. At each step of level order traversal, get two nodes from the queue, check for their equality and then insert next two children nodes of these nodes which need to be checked for equality. During insertion step, first left child of first tree node and right child of second tree node are inserted. After this right child of first tree node and left child of second tree node are inserted. If at any stage one node is NULL and other is not, then both trees are not a mirror of each other.
Steps to solve this problem:
1. Check if a is null and b is null than return yes.
2. Check if a is null or b is null than return no.
3. Declare a queue q of pointer to a node and push a and b in it.
4. While q is not empty:
  *Update a=q.front and pop the element.
  *Update b=q.front and pop the element.
  *Check if a->data is not equal to b->data than return no.
  *Check if a->left is not null and b->right is not null than push a->left and b->right in the q.
  *Else check if a->right is null or b ->left is not null than return no.
5. Return yes.
Below is the implementation of above approach:
C++
// C++ implementation to check whether the two// binary trees are mirrors of each other or not#include <bits/stdc++.h>using namespace std;Â
// Structure of a node in binary treestruct Node {Â Â Â Â int data;Â Â Â Â struct Node *left, *right;};Â
// Function to create and return// a new node for a binary treestruct Node* newNode(int data){Â Â Â Â struct Node* temp = new Node();Â Â Â Â temp->data = data;Â Â Â Â temp->left = temp->right = NULL;Â Â Â Â return temp;}Â
// Function to check whether the two binary trees// are mirrors of each other or notstring areMirrors(Node* a, Node* b){    // If both are NULL, then are mirror.    if (a == NULL && b == NULL)        return "Yes";Â
    // If only one is NULL, then not    // mirror.    if (a == NULL || b == NULL)        return "No";Â
    queue<Node*> q;Â
    // Push root of both trees in queue.    q.push(a);    q.push(b);Â
    while (!q.empty()) {Â
        // Pop two elements of queue, to        // get two nodes and check if they        // are symmetric.        a = q.front();        q.pop();Â
        b = q.front();        q.pop();Â
        // If data value of both nodes is        // not same, then not mirror.        if (a->data != b->data)            return "No";Â
        // Push left child of first tree node        // and right child of second tree node        // into queue if both are not NULL.        if (a->left && b->right) {            q.push(a->left);            q.push(b->right);        }Â
        // If any one of the nodes is NULL and        // other is not NULL, then not mirror.        else if (a->left || b->right)            return "No";Â
        // Push right child of first tree node        // and left child of second tree node        // into queue if both are not NULL.        if (a->right && b->left) {            q.push(a->right);            q.push(b->left);        }Â
        // If any one of the nodes is NULL and        // other is not NULL, then not mirror.        else if (a->right || b->left)            return "No";    }Â
    return "Yes";}// Driver Codeint main(){    // 1st binary tree formation    /*            1            / \           3  2             / \            5  4        */    Node* root1 = newNode(1);    root1->left = newNode(3);    root1->right = newNode(2);    root1->right->left = newNode(5);    root1->right->right = newNode(4);Â
    // 2nd binary tree formation    /*            1            / \           2  3         / \        4  5        */    Node* root2 = newNode(1);    root2->left = newNode(2);    root2->right = newNode(3);    root2->left->left = newNode(4);    root2->left->right = newNode(5);Â
    cout << areMirrors(root1, root2);    return 0;} |
Java
// Java implementation to check whether the two// binary trees are mirrors of each other or notimport java.util.*;Â
class GFG{Â
// Structure of a node in binary treestatic class Node {Â Â Â Â int data;Â Â Â Â Node left, right;};Â
// Function to create and return// a new node for a binary treestatic Node newNode(int data){Â Â Â Â Node temp = new Node();Â Â Â Â temp.data = data;Â Â Â Â temp.left = temp.right = null;Â Â Â Â return temp;}Â
// Function to check whether the two binary trees// are mirrors of each other or notstatic String areMirrors(Node a, Node b){    // If both are null, then are mirror.    if (a == null && b == null)        return "Yes";Â
    // If only one is null, then not    // mirror.    if (a == null || b == null)        return "No";Â
    Queue<Node> q = new LinkedList<Node>();Â
    // Push root of both trees in queue.    q.add(a);    q.add(b);Â
    while (q.size() > 0)     {Â
        // remove two elements of queue, to        // get two nodes and check if they        // are symmetric.        a = q.peek();        q.remove();Â
        b = q.peek();        q.remove();Â
        // If data value of both nodes is        // not same, then not mirror.        if (a.data != b.data)            return "No";Â
        // Push left child of first tree node        // and right child of second tree node        // into queue if both are not null.        if (a.left != null && b.right != null)         {            q.add(a.left);            q.add(b.right);        }Â
        // If any one of the nodes is null and        // other is not null, then not mirror.        else if (a.left != null || b.right != null)            return "No";Â
        // Push right child of first tree node        // and left child of second tree node        // into queue if both are not null.        if (a.right != null && b.left != null)        {            q.add(a.right);            q.add(b.left);        }Â
        //If any one of the nodes is null and        // other is not null, then not mirror.        else if (a.right != null || b.left != null)            return "No";    }Â
    return "Yes";}Â
// Driver Codepublic static void main(String args[]){    // 1st binary tree formation    /*            1         / \         3 2            / \            5 4        */    Node root1 = newNode(1);    root1.left = newNode(3);    root1.right = newNode(2);    root1.right.left = newNode(5);    root1.right.right = newNode(4);Â
    // 2nd binary tree formation    /*            1         / \         2 3        / \        4 5        */    Node root2 = newNode(1);    root2.left = newNode(2);    root2.right = newNode(3);    root2.left.left = newNode(4);    root2.left.right = newNode(5);Â
    System.out.print(areMirrors(root1, root2));}}Â
// This code is contributed by Arnab Kundu |
Python3
# Python3 implementation to check whether the two # binary trees are mirrors of each other or not Â
# Structure of a node in binary tree class Node:          def __init__(self, data):        self.data = data        self.left = None        self.right = None     # Function to check whether the two binary # trees are mirrors of each other or not def areMirrors(a, b):       # If both are NULL, then are mirror.     if a == None and b == None:        return "Yes"Â
    # If only one is NULL, then not mirror.     if a == None or b == None:         return "No"Â
    q = [] Â
    # append root of both trees in queue.     q.append(a)     q.append(b) Â
    while len(q) > 0: Â
        # Pop two elements of queue,         # to get two nodes and check         # if they are symmetric.         a = q.pop(0)        b = q.pop(0) Â
        # If data value of both nodes is         # not same, then not mirror.         if a.data != b.data:             return "No"Â
        # append left child of first tree node         # and right child of second tree node         # into queue if both are not NULL.         if a.left and b.right:             q.append(a.left)             q.append(b.right) Â
        # If any one of the nodes is NULL and         # other is not NULL, then not mirror.         elif a.left or b.right:             return "No"Â
        # Append right child of first tree node         # and left child of second tree node         # into queue if both are not NULL.         if a.right and b.left:             q.append(a.right)             q.append(b.left) Â
        # If any one of the nodes is NULL and         # other is not NULL, then not mirror.         elif a.right or b.left:             return "No"          return "Yes"  # Driver Code if __name__ == "__main__":       # 1st binary tree formation     root1 = Node(1)     root1.left = Node(3)     root1.right = Node(2)     root1.right.left = Node(5)     root1.right.right = Node(4) Â
    # 2nd binary tree formation     root2 = Node(1)     root2.left = Node(2)     root2.right = Node(3)     root2.left.left = Node(4)     root2.left.right = Node(5) Â
    print(areMirrors(root1, root2))Â
# This code is contributed by Rituraj Jain |
C#
// C# implementation to check whether the two// binary trees are mirrors of each other or notusing System;using System.Collections.Generic;Â
class GFG{Â
// Structure of a node in binary treepublic class Node {Â Â Â Â public int data;Â Â Â Â public Node left, right;};Â
// Function to create and return// a new node for a binary treestatic Node newNode(int data){Â Â Â Â Node temp = new Node();Â Â Â Â temp.data = data;Â Â Â Â temp.left = temp.right = null;Â Â Â Â return temp;}Â
// Function to check whether the two binary trees// are mirrors of each other or notstatic String areMirrors(Node a, Node b){    // If both are null, then are mirror.    if (a == null && b == null)        return "Yes";Â
    // If only one is null, then not    // mirror.    if (a == null || b == null)        return "No";Â
    Queue<Node> q = new Queue<Node>();Â
    // Push root of both trees in queue.    q.Enqueue(a);    q.Enqueue(b);Â
    while (q.Count > 0)     {Â
        // remove two elements of queue, to        // get two nodes and check if they        // are symmetric.        a = q.Peek();        q.Dequeue();Â
        b = q.Peek();        q.Dequeue();Â
        // If data value of both nodes is        // not same, then not mirror.        if (a.data != b.data)            return "No";Â
        // Push left child of first tree node        // and right child of second tree node        // into queue if both are not null.        if (a.left != null && b.right != null)         {            q.Enqueue(a.left);            q.Enqueue(b.right);        }Â
        // If any one of the nodes is null and        // other is not null, then not mirror.        else if (a.left != null || b.right != null)            return "No";Â
        // Push right child of first tree node        // and left child of second tree node        // into queue if both are not null.        if (a.right != null && b.left != null)        {            q.Enqueue(a.right);            q.Enqueue(b.left);        }Â
        //If any one of the nodes is null and        // other is not null, then not mirror.        else if (a.right != null || b.left != null)            return "No";    }    return "Yes";}Â
// Driver Codepublic static void Main(String []args){    // 1st binary tree formation    /*            1         / \         3 2            / \            5 4        */    Node root1 = newNode(1);    root1.left = newNode(3);    root1.right = newNode(2);    root1.right.left = newNode(5);    root1.right.right = newNode(4);Â
    // 2nd binary tree formation    /*            1         / \         2 3        / \        4 5        */    Node root2 = newNode(1);    root2.left = newNode(2);    root2.right = newNode(3);    root2.left.left = newNode(4);    root2.left.right = newNode(5);Â
    Console.Write(areMirrors(root1, root2));}}Â
// This code is contributed by Princi Singh |
Javascript
<script>Â
// JavaScript implementation to check whether the two// binary trees are mirrors of each other or notÂ
// Structure of a node in binary treeclass Node {Â Â Â Â constructor()Â Â Â Â {Â Â Â Â Â Â Â Â this.data = 0;Â Â Â Â Â Â Â Â this.left = null;Â Â Â Â Â Â Â Â this.right = null;Â Â Â Â }};Â
// Function to create and return// a new node for a binary treefunction newNode(data){Â Â Â Â var temp = new Node();Â Â Â Â temp.data = data;Â Â Â Â temp.left = temp.right = null;Â Â Â Â return temp;}Â
// Function to check whether the two binary trees// are mirrors of each other or notfunction areMirrors(a, b){    // If both are null, then are mirror.    if (a == null && b == null)        return "Yes";Â
    // If only one is null, then not    // mirror.    if (a == null || b == null)        return "No";Â
    var q = [];Â
    // Push root of both trees in queue.    q.push(a);    q.push(b);Â
    while (q.length > 0)     {Â
        // remove two elements of queue, to        // get two nodes and check if they        // are symmetric.        a = q[0];        q.shift();Â
        b = q[0];        q.shift();Â
        // If data value of both nodes is        // not same, then not mirror.        if (a.data != b.data)            return "No";Â
        // Push left child of first tree node        // and right child of second tree node        // into queue if both are not null.        if (a.left != null && b.right != null)         {            q.push(a.left);            q.push(b.right);        }Â
        // If any one of the nodes is null and        // other is not null, then not mirror.        else if (a.left != null || b.right != null)            return "No";Â
        // Push right child of first tree node        // and left child of second tree node        // into queue if both are not null.        if (a.right != null && b.left != null)        {            q.push(a.right);            q.push(b.left);        }Â
        //If any one of the nodes is null and        // other is not null, then not mirror.        else if (a.right != null || b.left != null)            return "No";    }    return "Yes";}Â
// Driver Code// 1st binary tree formation/*Â Â Â Â Â Â Â Â 1 Â Â Â Â / \ Â Â Â Â 3 2Â Â Â Â Â Â Â Â / \Â Â Â Â Â Â Â Â 5 4Â Â Â Â */var root1 = newNode(1);root1.left = newNode(3);root1.right = newNode(2);root1.right.left = newNode(5);root1.right.right = newNode(4);// 2nd binary tree formation/*Â Â Â Â Â Â Â Â 1 Â Â Â Â / \ Â Â Â Â 2 3Â Â Â Â / \Â Â Â Â 4 5Â Â Â Â */var root2 = newNode(1);root2.left = newNode(2);root2.right = newNode(3);root2.left.left = newNode(4);root2.left.right = newNode(5);document.write(areMirrors(root1, root2));Â
Â
</script> |
Yes
Complexity Analysis:
- Time complexity: O(N)
Auxiliary Space: O(N)Â Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!




