Open In App

Symmetric Tree (Mirror Image of itself)

Last Updated : 22 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary tree, check whether it is a mirror of itself.

For example, this binary tree is symmetric: 

     1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Recommended Practice

The idea is to write a recursive function isMirror() that takes two trees as an argument and returns true if trees are the mirror and false if trees are not mirrored. The isMirror() function recursively checks two roots and subtrees under the root.

Below is the implementation of the above algorithm.

C++
// C++ program to check if a given Binary Tree is symmetric
// or not
#include <bits/stdc++.h>
using namespace std;

// A Binary Tree Node
struct Node {
    int key;
    struct Node *left, *right;
};

// Utility function to create new Node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}

// Returns true if trees with roots as root1 and root2 are
// mirror
bool isMirror(struct Node* root1, struct Node* root2)
{
    // If both trees are empty, then they are mirror images
    if (root1 == NULL && root2 == NULL)
        return true;

    // For two trees to be mirror images, the following
    // three conditions must be true
    // 1.) Their root node's key must be same
    // 2.) left subtree of left tree and right subtree of
    // right tree have to be mirror images
    // 3.) right subtree of left tree and left subtree of
    // right tree have to be mirror images
    if (root1 && root2 && root1->key == root2->key)
        return isMirror(root1->left, root2->right)
               && isMirror(root1->right, root2->left);

    // if none of above conditions is true then root1
    // and root2 are not mirror images
    return false;
}

// Returns true if a tree is symmetric i.e. mirror image of itself
bool isSymmetric(struct Node* root)
{
    // Check if tree is mirror of itself
    return isMirror(root, root);
}

// Driver code
int main()
{
    // Let us construct the Tree shown in the above figure
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(2);
    root->left->left = newNode(3);
    root->left->right = newNode(4);
    root->right->left = newNode(4);
    root->right->right = newNode(3);

    if (isSymmetric(root))
        cout << "Symmetric";
    else
        cout << "Not symmetric";
    return 0;
}

// This code is contributed by Sania Kumari Gupta
C
// C program to check if a given Binary Tree is symmetric
// or not
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

// A Binary Tree Node
typedef struct Node {
    int key;
    struct Node *left, *right;
} Node;

// Utility function to create new Node
Node* newNode(int key)
{
    Node* temp = (Node *)malloc(sizeof(Node));
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}

// Returns true if trees with roots as root1 and root2 are
// mirror
bool isMirror(Node* root1, Node* root2)
{
    // If both trees are empty, then they are mirror images
    if (root1 == NULL && root2 == NULL)
        return true;

    // For two trees to be mirror images, the following
    // three conditions must be true
    // 1.) Their root node's key must be same
    // 2.) left subtree of left tree and right subtree of
    // right tree have to be mirror images
    // 3.) right subtree of left tree and left subtree of
    // right tree have to be mirror images
    if (root1 && root2 && root1->key == root2->key)
        return isMirror(root1->left, root2->right)
               && isMirror(root1->right, root2->left);

    // if none of above conditions is true then root1
    // and root2 are not mirror images
    return false;
}

// Returns true if a tree is symmetric i.e. mirror image of
// itself
bool isSymmetric(Node* root)
{
    // Check if tree is mirror of itself
    return isMirror(root, root);
}

// Driver code
int main()
{
    // Let us construct the Tree shown in the above figure
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(2);
    root->left->left = newNode(3);
    root->left->right = newNode(4);
    root->right->left = newNode(4);
    root->right->right = newNode(3);

    if (isSymmetric(root))
        printf("Symmetric");
    else
        printf("Not symmetric");
    return 0;
}

// This code is contributed by Sania Kumari Gupta
Java
// Java program to check is binary tree is symmetric or not
class Node {
    int key;
    Node left, right;
    Node(int item)
    {
        key = item;
        left = right = null;
    }
}

class BinaryTree {
    Node root;

    // returns true if trees with roots as root1 and
    // root2 are mirror
    boolean isMirror(Node node1, Node node2)
    {
        // if both trees are empty, then they are mirror image
        if (node1 == null && node2 == null)
            return true;

        // For two trees to be mirror images, the following
        // three conditions must be true
        // 1.) Their root node's key must be same
        // 2.) left subtree of left tree and right subtree
        // of right tree have to be mirror images
        // 3.) right subtree of left tree and left subtree
        // of right tree have to be mirror images
        if (node1 != null && node2 != null
            && node1.key == node2.key)
            return (isMirror(node1.left, node2.right)
                    && isMirror(node1.right, node2.left));

        // if none of the above conditions is true then
        // root1 and root2 are not mirror images
        return false;
    }

    // returns true if the tree is symmetric i.e
    // mirror image of itself
    boolean isSymmetric()
    {
        // check if tree is mirror of itself
        return isMirror(root, root);
    }

    // Driver code
    public static void main(String args[])
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(2);
        tree.root.left.left = new Node(3);
        tree.root.left.right = new Node(4);
        tree.root.right.left = new Node(4);
        tree.root.right.right = new Node(3);
        boolean output = tree.isSymmetric();
        if (output == true)
            System.out.println("Symmetric");
        else
            System.out.println("Not symmetric");
    }
}

// This code is contributed by Sania Kumari Gupta
Python
# Python program to check if a 
# given Binary Tree is symmetric or not

# Node structure


class Node:

    # Utility function to create new node
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

# Returns True if trees 
#with roots as root1 and root 2  are mirror


def isMirror(root1, root2):
    # If both trees are empty, then they are mirror images
    if root1 is None and root2 is None:
        return True

    """ For two trees to be mirror images, 
        the following three conditions must be true
        1 - Their root node's key must be same
        2 - left subtree of left tree and right subtree
          of the right tree have to be mirror images
        3 - right subtree of left tree and left subtree
           of right tree have to be mirror images
    """
    if (root1 is not None and root2 is not None):
        if root1.key == root2.key:
            return (isMirror(root1.left, root2.right)and
                    isMirror(root1.right, root2.left))

    # If none of the above conditions is true then root1
    # and root2 are not mirror images
    return False


def isSymmetric(root):

    # Check if tree is mirror of itself
    return isMirror(root, root)


# Driver Code
# Let's construct the tree show in the above figure
root = Node(1)
root.left = Node(2)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.right.left = Node(4)
root.right.right = Node(3)
print ("Symmetric" if isSymmetric(root) == True else "Not symmetric")

# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
// C# program to check is binary
// tree is symmetric or not
using System;

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

    public Node(int item)
    {
        key = item;
        left = right = null;
    }
}

class GFG {
    Node root;

    // returns true if trees with roots
    // as root1 and root2 are mirror
    Boolean isMirror(Node node1, Node node2)
    {
        // if both trees are empty,
        // then they are mirror image
        if (node1 == null && node2 == null)
            return true;

        // For two trees to be mirror images,
        // the following three conditions must be true
        // 1 - Their root node's key must be same
        // 2 - left subtree of left tree and right 
        // subtree of right tree have to be mirror images
        // 3 - right subtree of left tree and left subtree
        // of right tree have to be mirror images
        if (node1 != null && node2 != null
            && node1.key == node2.key)
            return (isMirror(node1.left, node2.right)
                    && isMirror(node1.right, node2.left));

        // if none of the above conditions
        // is true then root1 and root2 are
        // mirror images
        return false;
    }

    // returns true if the tree is symmetric
    // i.e mirror image of itself
    Boolean isSymmetric()
    {
        // check if tree is mirror of itself
        return isMirror(root, root);
    }

    // Driver Code
    static public void Main(String[] args)
    {
        GFG tree = new GFG();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(2);
        tree.root.left.left = new Node(3);
        tree.root.left.right = new Node(4);
        tree.root.right.left = new Node(4);
        tree.root.right.right = new Node(3);
        Boolean output = tree.isSymmetric();
        if (output == true)
            Console.WriteLine("Symmetric");
        else
            Console.WriteLine("Not symmetric");
    }
}

// This code is contributed by Arnab Kundu
Javascript
// Javascript program to check is binary
// tree is symmetric or not

class Node {

  constructor(item)
  {
    this.key = item;
    this.left = null;
    this.right = null;
  }
}

var root = null;

// returns true if trees with roots
// as root1 and root2 are mirror
function isMirror(node1, node2)
{
    // if both trees are empty,
    // then they are mirror image
    if (node1 == null && node2 == null)
        return true;
        
    // For two trees to be mirror images,
    // the following three conditions must be true
    // 1 - Their root node's key must be same
    // 2 - left subtree of left tree and right 
    // subtree of right tree have to be mirror images
    // 3 - right subtree of left tree and left subtree
    // of right tree have to be mirror images
    if (node1 != null && node2 != null
        && node1.key == node2.key)
        return (isMirror(node1.left, node2.right)
                && isMirror(node1.right, node2.left));
                
    // if none of the above conditions
    // is true then root1 and root2 are
    // mirror images
    return false;
}

// returns true if the tree is symmetric
// i.e mirror image of itself
function isSymmetric()
{

    // check if tree is mirror of itself
    return isMirror(root, root);
}

// Driver Code
root = new Node(1);
root.left = new Node(2);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(4);
root.right.left = new Node(4);
root.right.right = new Node(3);
var output = isSymmetric();
if (output == true)
    console.log("Symmetric");
else
    console.log("Not symmetric");

// This code is contributed by rrrtnx.

Output
Symmetric

Time Complexity: O(N)
Auxiliary Space: O(h) where h is the maximum height of the tree

Iterative Approach:

Algorithm for checking whether a binary tree is a mirror of itself using an iterative approach and a stack:

  1. Create a stack and push the root node onto it twice.
  2. While the stack is not empty, repeat the following steps:
       a. Pop two nodes from the stack, say node1 and node2.
       b. If both node1 and node2 are null, continue to the next iteration.
       c. If one of the nodes is null and the other is not, return false as it is not a mirror.
       d. If both nodes are not null, compare their values. If they are not equal, return false.
       e. Push the left child of node1 and the right child of node2 onto the stack.
       f. Push the right child of node1 and the left child of node2 onto the stack.
  3. If the loop completes successfully without returning false, return true as it is a mirror.
C++
// C++ program to check if a given Binary Tree is symmetric
// or not
#include <bits/stdc++.h>
using namespace std;

// A Binary Tree Node
struct Node {
    int key;
    struct Node *left, *right;
};

// Utility function to create new Node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}

// Returns true if a tree is symmetric i.e. mirror image of
// itself
bool isSymmetric(Node* root){
    // If the root is null, then the binary tree is
    // symmetric.
    if (root == NULL) {
        return true;
    }

    // Create a stack to store the left and right subtrees
    // of the root.
    stack<Node*> stack;
    stack.push(root->left);
    stack.push(root->right);

    // Continue the loop until the stack is empty.
    while (!stack.empty()) {
        // Pop the left and right subtrees from the stack.
        Node* node1 = stack.top();
          stack.pop();
        Node* node2 = stack.top();
          stack.pop();

        // If both nodes are null, continue the loop.
        if (node1 == NULL && node2 == NULL) {
            continue;
        }

        // If one of the nodes is null, the binary tree is
        // not symmetric.
        if (node1 == NULL || node2 == NULL) {
            return false;
        }

        // If the values of the nodes are not equal, the
        // binary tree is not symmetric.
        if (node1->key != node2->key) {
            return false;
        }

        // Push the left and right subtrees of the left and
        // right nodes onto the stack in the opposite order.
        stack.push(node1->left);
        stack.push(node2->right);
        stack.push(node1->right);
        stack.push(node2->left);
    }

    // If the loop completes, the binary tree is symmetric.
    return true;
}

// Driver code
int main()
{
    // Let us construct the Tree shown in the above figure
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(2);
    root->left->left = newNode(3);
    root->left->right = newNode(4);
    root->right->left = newNode(4);
    root->right->right = newNode(3);

    if (isSymmetric(root))
        cout << "Symmetric";
    else
        cout << "Not symmetric";
    return 0;
}

// This code is contributed by sramshyam
Java
// Java program to check if a given Binary Tree is symmetric
// or not
import java.util.*;

// A Binary Tree Node
class Node {
  int key;
  Node left, right;
  // Constructor
  Node(int item)
  {
    key = item;
    left = right = null;
  }
}

public class GFG 
{
  
  // Returns true if a tree is symmetric i.e. mirror image
  // of itself
  static boolean isSymmetric(Node root)
  {
    
    // If the root is null, then the binary tree is
    // symmetric.
    if (root == null) {
      return true;
    }
    
    // Create a stack to store the left and right
    // subtrees
    // of the root.
    Stack<Node> stack = new Stack<>();
    stack.push(root.left);
    stack.push(root.right);

    // Continue the loop until the stack is empty.
    while (!stack.empty()) {
      // Pop the left and right subtrees from the
      // stack.
      Node node1 = stack.pop();
      Node node2 = stack.pop();

      // If both nodes are null, continue the loop.
      if (node1 == null && node2 == null) {
        continue;
      }

      // If one of the nodes is null, the binary tree
      // is not symmetric.
      if (node1 == null || node2 == null) {
        return false;
      }

      // If the values of the nodes are not equal, the
      // binary tree is not symmetric.
      if (node1.key != node2.key) {
        return false;
      }

      // Push the left and right subtrees of the left
      // and right nodes onto the stack in the
      // opposite order.
      stack.push(node1.left);
      stack.push(node2.right);
      stack.push(node1.right);
      stack.push(node2.left);
    }

    // If the loop completes, the binary tree is
    // symmetric.
    return true;
  }

  // Driver code
  public static void main(String[] args)
  {
    // Let us construct the Tree shown in the above
    // figure
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(2);
    root.left.left = new Node(3);
    root.left.right = new Node(4);
    root.right.left = new Node(4);
    root.right.right = new Node(3);

    if (isSymmetric(root))
      System.out.println("Symmetric");
    else
      System.out.println("Not symmetric");
  }
}
Python
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

def isSymmetric(root):
    # If the root is null, then the binary tree is symmetric
    if not root:
        return True
    
    # Create a stack to store the left and right subtrees of the root
    stack = []
    stack.append(root.left)
    stack.append(root.right)
    
    # Continue the loop until the stack is empty
    while stack:
        # Pop the left and right subtrees from the stack
        node1 = stack.pop()
        node2 = stack.pop()
        
        # If both nodes are null, continue the loop
        if not node1 and not node2:
            continue
        
        # If one of the nodes is null, the binary tree is not symmetric
        if not node1 or not node2:
            return False
        
        # If the values of the nodes are not equal, the binary tree is not symmetric
        if node1.key != node2.key:
            return False
        
        # Push the left and right subtrees of the left and right nodes onto the stack in the opposite order
        stack.append(node1.left)
        stack.append(node2.right)
        stack.append(node1.right)
        stack.append(node2.left)
    
    # If the loop completes, the binary tree is symmetric
    return True

# Driver code
root = Node(1)
root.left = Node(2)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.right.left = Node(4)
root.right.right = Node(3)

if isSymmetric(root):
    print("Symmetric")
else:
    print("Not symmetric")
C#
using System;
using System.Collections;

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

    // Constructor
    public Node(int item)
    {
        key = item;
        left = right = null;
    }
}

public class GFG
{
    // Returns true if a tree is symmetric i.e. mirror image
    // of itself
    static bool isSymmetric(Node root)
    {
        // If the root is null, then the binary tree is
        // symmetric.
        if (root == null)
        {
            return true;
        }

        // Create a stack to store the left and right subtrees
        // of the root.
        Stack stack = new Stack();
        stack.Push(root.left);
        stack.Push(root.right);

        // Continue the loop until the stack is empty.
        while (stack.Count != 0)
        {
            // Pop the left and right subtrees from the stack.
            Node node1 = (Node)stack.Pop();
            Node node2 = (Node)stack.Pop();

            // If both nodes are null, continue the loop.
            if (node1 == null && node2 == null)
            {
                continue;
            }

            // If one of the nodes is null, the binary tree
            // is not symmetric.
            if (node1 == null || node2 == null)
            {
                return false;
            }

            // If the values of the nodes are not equal, the
            // binary tree is not symmetric.
            if (node1.key != node2.key)
            {
                return false;
            }

            // Push the left and right subtrees of the left
            // and right nodes onto the stack in the
            // opposite order.
            stack.Push(node1.left);
            stack.Push(node2.right);
            stack.Push(node1.right);
            stack.Push(node2.left);
        }

        // If the loop completes, the binary tree is
        // symmetric.
        return true;
    }

    // Driver code
    public static void Main(string[] args)
    {
        // Let us construct the Tree shown in the above
        // figure
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(2);
        root.left.left = new Node(3);
        root.left.right = new Node(4);
        root.right.left = new Node(4);
        root.right.right = new Node(3);

        if (isSymmetric(root))
            Console.WriteLine("Symmetric");
        else
            Console.WriteLine("Not symmetric");
    }
}
Javascript
// Node class for binary tree
class Node {
    constructor(item) {
        this.key = item;
        this.left = null;
        this.right = null;
    }
}

// Returns true if a tree is symmetric i.e. mirror image of itself
function isSymmetric(root) {
    // If the root is null, then the binary tree is symmetric.
    if (root === null) {
        return true;
    }

    // Create a stack to store the left and right subtrees of the root.
    const stack = [];
    stack.push(root.left);
    stack.push(root.right);

    // Continue the loop until the stack is empty.
    while (stack.length > 0) {
        // Pop the left and right subtrees from the stack.
        const node1 = stack.pop();
        const node2 = stack.pop();

        // If both nodes are null, continue the loop.
        if (node1 === null && node2 === null) {
            continue;
        }

        // If one of the nodes is null, the binary tree is not symmetric.
        if (node1 === null || node2 === null) {
            return false;
        }

        // If the values of the nodes are not equal, the binary tree is not symmetric.
        if (node1.key !== node2.key) {
            return false;
        }

        // Push the left and right subtrees of the left and right nodes onto the stack in the opposite order.
        stack.push(node1.left);
        stack.push(node2.right);
        stack.push(node1.right);
        stack.push(node2.left);
    }

    // If the loop completes, the binary tree is symmetric.
    return true;
}

// Driver code
(function() {
    // Let us construct the Tree shown in the above figure
    const root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(2);
    root.left.left = new Node(3);
    root.left.right = new Node(4);
    root.right.left = new Node(4);
    root.right.right = new Node(3);

    if (isSymmetric(root)) {
        console.log("Symmetric");
    } else {
        console.log("Not symmetric");
    }
})();

Output
Symmetric

Time Complexity: O(n) where n is the number of nodes.
Space Complexity: O(h) where h is the height of the tree. 

Iterative approach using a queue:

The basic idea is to check if the left and right subtrees of the root node are mirror images of each other. 
To do this, we perform a level-order traversal of the binary tree using a queue. We push the root node into the queue twice, initially.
We dequeue two nodes at a time from the front of the queue and check if they are mirror images of each other.

Follow the steps to solve the problem:

  1. If the root node is NULL, return true as an empty binary tree is considered symmetric.
  2. Create a queue and push the root node twice into the queue.
  3. While the queue is not empty, dequeue two nodes at a time, one for the left subtree and one for the right subtree.
  4. If both the left and right nodes are NULL, continue to the next iteration as the subtrees are considered mirror images of each other.
  5. If either the left or right node is NULL, or their data is not equal, return false as they are not mirror images of each other.
  6. Push the left and right nodes of the left subtree into the queue, followed by the right and left nodes of the right subtree into the queue.
  7. If the queue becomes empty and we have not returned false till now, return true as the binary tree is symmetric.

Below is the implementation of the above approach:

C++
// C++ code to implement the iterative approach using a
// queue
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
    Node(int val)
    {
        data = val;
        left = NULL;
        right = NULL;
    }
};

bool isSymmetric(struct Node* root)
{
    if (root == NULL) {
        return true;
    }

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

    while (!q.empty()) {
        Node* leftNode = q.front();
        q.pop();
        Node* rightNode = q.front();
        q.pop();

        // If both leftNode and rightNode are NULL, continue
        // to the next iteration
        if (leftNode == NULL && rightNode == NULL) {
            continue;
        }

        // If either leftNode or rightNode is NULL or their
        // data is not equal, return false
        if (leftNode == NULL || rightNode == NULL
            || leftNode->data != rightNode->data) {
            return false;
        }

        // Pushing the left and right nodes of the current
        // node into the queue
        q.push(leftNode->left);
        q.push(rightNode->right);
        q.push(leftNode->right);
        q.push(rightNode->left);
    }
    return true;
}
// Driver Code
int main()
{
    // Creating a binary tree
    struct Node* root = new Node(5);
    root->left = new Node(1);
    root->right = new Node(1);
    root->left->left = new Node(2);
    root->right->right = new Node(2);

    // Checking if the binary tree is symmetric or not
    if (isSymmetric(root)) {
        cout << "The binary tree is symmetric\n";
    }
    else {
        cout << "The binary tree is not symmetric\n";
    }

    return 0;
}
// This Code is contributed by Veerendra_Singh_Rajpoot
Java
//Java code to implement the iterative approach using a queue
import java.util.LinkedList;
import java.util.Queue;

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

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

public class SymmetricBinaryTree {
  //Function to implement the iterative approach using a queue
    public static boolean isSymmetric(Node root) {
        if (root == null) {
            return true;
        }

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

        while (!q.isEmpty()) {
            Node leftNode = q.poll();
            Node rightNode = q.poll();

            // If both leftNode and rightNode are null, continue
            // to the next iteration
            if (leftNode == null && rightNode == null) {
                continue;
            }

            // If either leftNode or rightNode is null or their
            // data is not equal, return false
            if (leftNode == null || rightNode == null || leftNode.data != rightNode.data) {
                return false;
            }

            // Pushing the left and right nodes of the current
            // node into the queue
            q.add(leftNode.left);
            q.add(rightNode.right);
            q.add(leftNode.right);
            q.add(rightNode.left);
        }
        return true;
    }
//Driver Code
    public static void main(String[] args) {
        // Creating a binary tree
        Node root = new Node(5);
        root.left = new Node(1);
        root.right = new Node(1);
        root.left.left = new Node(2);
        root.right.right = new Node(2);

        // Checking if the binary tree is symmetric or not
        if (isSymmetric(root)) {
            System.out.println("The binary tree is symmetric");
        } else {
            System.out.println("The binary tree is not symmetric");
        }
    }
}
//This code is contributed by Veerendra_Singh_Rajpoot
Python
from queue import Queue

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

def isSymmetric(root):
    if root is None:
        return True

    q = Queue()
    q.put(root)
    q.put(root)

    while not q.empty():
        leftNode = q.get()
        rightNode = q.get()

        # If both leftNode and rightNode are None, continue
        # to the next iteration
        if leftNode is None and rightNode is None:
            continue

        # If either leftNode or rightNode is None or their
        # data is not equal, return False
        if leftNode is None or rightNode is None or leftNode.data != rightNode.data:
            return False

        # Pushing the left and right nodes of the current
        # node into the queue
        q.put(leftNode.left)
        q.put(rightNode.right)
        q.put(leftNode.right)
        q.put(rightNode.left)

    return True

if __name__ == '__main__':
    # Creating a binary tree
    root = Node(5)
    root.left = Node(1)
    root.right = Node(1)
    root.left.left = Node(2)
    root.right.right = Node(2)

    # Checking if the binary tree is symmetric or not
    if isSymmetric(root):
        print("The binary tree is symmetric")
    else:
        print("The binary tree is not symmetric")
C#
using System;
using System.Collections.Generic;

public class Node
{
    public int Data;
    public Node Left;
    public Node Right;

    public Node(int val)
    {
        Data = val;
        Left = null;
        Right = null;
    }
}

public class BinaryTree
{
    public static bool IsSymmetric(Node root)
    {
        if (root == null)
        {
            return true;
        }

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

        while (queue.Count > 0)
        {
            Node leftNode = queue.Dequeue();
            Node rightNode = queue.Dequeue();

            // If both leftNode and rightNode are null, continue to the next iteration
            if (leftNode == null && rightNode == null)
            {
                continue;
            }

            // If either leftNode or rightNode is null or their data is not equal, return false
            if (leftNode == null || rightNode == null || leftNode.Data != rightNode.Data)
            {
                return false;
            }

            // Pushing the left and right nodes of the current node into the queue
            queue.Enqueue(leftNode.Left);
            queue.Enqueue(rightNode.Right);
            queue.Enqueue(leftNode.Right);
            queue.Enqueue(rightNode.Left);
        }
        return true;
    }

    public static void Main(string[] args)
    {
        // Creating a binary tree
        Node root = new Node(5);
        root.Left = new Node(1);
        root.Right = new Node(1);
        root.Left.Left = new Node(2);
        root.Right.Right = new Node(2);

        // Checking if the binary tree is symmetric or not
        if (IsSymmetric(root))
        {
            Console.WriteLine("The binary tree is symmetric");
        }
        else
        {
            Console.WriteLine("The binary tree is not symmetric");
        }
    }
}
Javascript
//Javascript code for the above approach
class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

function isSymmetric(root) {
    if (root === null) {
        return true;
    }

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

    while (q.length > 0) {
        const leftNode = q.shift();
        const rightNode = q.shift();

        // If both leftNode and rightNode are null, continue
        // to the next iteration
        if (leftNode === null && rightNode === null) {
            continue;
        }

        // If either leftNode or rightNode is null or their
        // data is not equal, return false
        if (leftNode === null || rightNode === null || leftNode.data !== rightNode.data) {
            return false;
        }

        // Pushing the left and right nodes of the current
        // node into the queue
        q.push(leftNode.left);
        q.push(rightNode.right);
        q.push(leftNode.right);
        q.push(rightNode.left);
    }
    return true;
}

// Driver Code
function main() {
    // Creating a binary tree
    const root = new Node(5);
    root.left = new Node(1);
    root.right = new Node(1);
    root.left.left = new Node(2);
    root.right.right = new Node(2);

    // Checking if the binary tree is symmetric or not
    if (isSymmetric(root)) {
        console.log("The binary tree is symmetric");
    } else {
        console.log("The binary tree is not symmetric");
    }
}

main();

Output
The binary tree is symmetric

Time Complexity: O(n),The time complexity of this approach is O(n), where n is the number of nodes in the binary tree.
This is because we visit each node of the binary tree once.

Space Complexity: O(n) , The space complexity of this approach is O(n), where n is the number of nodes in the binary tree.
This is because we store the nodes of the binary tree in a queue.
In the worst-case scenario, the queue can contain all the nodes of the binary tree at the last level, which is approximately n/2 nodes.



Previous Article
Next Article

Similar Reads

A square matrix as sum of symmetric and skew-symmetric matrices
Let A be a square matrix with all real number entries. Find two symmetric matrix P and skew symmetric matrix Q such that P + Q = A. Symmetric Matrix:- A square matrix is said to be symmetric matrix if the transpose of the matrix is same as the original matrix. Skew Symmetric Matrix:- A square matrix is said to be skew symmetric matrix if the negati
9 min read
Check if a number is prime in Flipped Upside Down, Mirror Flipped and Mirror Flipped Upside Down
Given an integer N, the task is to check if N is a prime number in Flipped Down, Mirror Flipped and Mirror Flipped Down forms of the given number.Examples: Input: N = 120121 Output: YesExplanation: Flipped forms of the number:Flipped Upside Down - 151051Mirror Flipped - 121021Mirror Upside Down - 150151Since 1510151 and 121021 are both prime number
6 min read
Convert a Binary Tree into its Mirror Tree (Invert Binary Tree)
Given a binary tree, the task is to convert the binary tree into its Mirror tree. Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Recommended PracticeMirror TreeTry It!The idea is to traverse recursively and swap the right and left subtrees after traversing the subtrees. Follow
15+ min read
Convert given Binary Tree to Symmetric Tree by adding minimum number of nodes
Given a Binary Tree, the task is to convert the given Binary Tree to the Symmetric Tree by adding the minimum number of nodes in the given Tree. Examples: Input: Output: Input: Output: Approach: To solve this problem, follow the below steps: Make a function buildSymmetricTree which will accept two parameters root1 and root2.Here, root1 and root2, a
8 min read
Sum of the mirror image nodes of a complete binary tree in an inorder way
Given a complete binary tree, the task is to find the sum of mirror image nodes in an inorder way i.e. find the inorder traversal of the left sub-tree and for every node traversed, add the value of its mirror node to the current node's value. Examples: Input: Output: 20 51 19 10 Inorder traversal of the left sub-tree of the given tree is 4 23 11 5.
6 min read
Number of edges in mirror image of Complete binary tree
Given a complete binary tree of depth H. If the mirror image from the left and the right side of this tree is taken then: Right Mirrored Image: Rightmost node of the every level is connected to mirrored corresponding node. Left Mirrored Image: Left most node of the every level is connected to mirrored corresponding node. The task is to find the num
4 min read
Create a mirror tree from the given binary tree
Given a binary tree, the task is to create a new binary tree which is a mirror image of the given binary tree. Examples: Input: 5 / \ 3 6 / \ 2 4 Output: Inorder of original tree: 2 3 4 5 6 Inorder of mirror tree: 6 5 4 3 2 Mirror tree will be: 5 / \ 6 3 / \ 4 2 Input: 2 / \ 1 8 / \ 12 9 Output: Inorder of original tree: 12 1 2 8 9 Inorder of mirro
14 min read
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traver
12 min read
Check whether every node of binary tree has a value K on itself or its any immediate neighbours
Given a binary tree and a value K, the task is to check if every node of the binary tree has either the value of the node as K or at least one of its adjacent connected nodes has the value K. Examples: Input: 1 / \ 0 0 / \ \ 1 0 1 / / \ \ 2 1 0 5 / / 3 0 / 0 K = 0 Output: False Explanation: We can observe that some leaf nodes are having value other
8 min read
Count nodes having highest value in the path from root to itself in a Binary Tree
Given a Binary Tree, the task is to count the number of nodes in the Binary Tree, which are the highest valued node in the path from the root up to that node. Examples: Input: Below is the given Tree: 3 / \ 2 5 / \ 4 6Output: 4Explanation:Root node satisfies the required condition.Node 5 is the highest valued node in the path (3 -&gt; 5).Node 6 is
8 min read
Article Tags :
Practice Tags :