Check for Symmetric Binary Tree (Iterative Approach) - GeeksforGeeks

11 Mar, 2022
Given a binary tree, check whether it is a mirror of itself without recursion.
Examples: 
Input :   
    
     1
   /   \
  2     2
 / \   / \
3   4 4   3

Output : Symmetric

Input :    
   
    1
   / \
  2   2
   \   \
   3    3

Output : Not Symmetric
We have discussed recursive approach to solve this problem in below post :Symmetric Tree (Mirror Image of itself)In this post, iterative approach is discussed. We use Queue here. Note that for a symmetric that elements at every level are palindromic. In example 2, at the leaf level- the elements are which is not palindromic. In other words, 1. The left child of left subtree = right child of right subtree. 2. The right child of left subtree = left child of right subtree. If we insert the left child of left subtree first followed by right child of the right subtree in the queue, we only need to ensure that these are equal. Similarly, If we insert the right child of left subtree followed by left child of the right subtree in the queue, we again need to ensure that these are equal.
Below is the implementation based on above idea. 
C++
Java
Python3
C#
Javascript
// C++ program to check if a given Binary// Tree is symmetric or not#include<bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{    int key;    struct Node* left, *right;}; // Utility function to create new NodeNode *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 itselfbool isSymmetric(struct Node* root){    if(root == NULL)        return true;         // If it is a single tree node, then    // it is a symmetric tree.    if(!root->left && !root->right)        return true;         queue <Node*> q;         // Add root to queue two times so that    // it can be checked if either one child    // alone is NULL or not.    q.push(root);    q.push(root);         // To store two nodes for checking their    // symmetry.    Node* leftNode, *rightNode;         while(!q.empty()){                 // Remove first two nodes to check        // their symmetry.        leftNode = q.front();        q.pop();                 rightNode = q.front();        q.pop();                 // if both left and right nodes        // exist, but have different        // values--> inequality, return false        if(leftNode->key != rightNode->key){        return false;        }                 // Push left child of left subtree node        // and right child of right subtree        // node in queue.        if(leftNode->left && rightNode->right){            q.push(leftNode->left);            q.push(rightNode->right);        }                 // If only one child is present alone        // and other is NULL, then tree        // is not symmetric.        else if (leftNode->left || rightNode->right)        return false;                 // Push right child of left subtree node        // and left child of right subtree node        // in queue.        if(leftNode->right && rightNode->left){            q.push(leftNode->right);            q.push(rightNode->left);        }                 // If only one child is present alone        // and other is NULL, then tree        // is not symmetric.        else if(leftNode->right || rightNode->left)        return false;    }         return true;} // Driver programint 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 << "The given tree is Symmetric";    else        cout << "The given tree is not Symmetric";    return 0;} // This code is contributed by Nikhil jindal.
// Iterative Java program to check if// given binary tree symmetricimport java.util.* ; public class BinaryTree{    Node root;    static class Node    {        int val;        Node left, right;        Node(int v)        {            val = v;            left = null;            right = null;        }    }     /* constructor to initialise the root */    BinaryTree(Node r) { root = r; }     /* empty constructor */    BinaryTree()  {  }      /* function to check if the tree is Symmetric */    public boolean isSymmetric(Node root)    {        /* This allows adding null elements to the queue */        Queue<Node> q = new LinkedList<Node>();         /* Initially, add left and right nodes of root */        q.add(root.left);        q.add(root.right);         while (!q.isEmpty())        {            /* remove the front 2 nodes to              check for equality */            Node tempLeft = q.remove();            Node tempRight = q.remove();             /* if both are null, continue and check               for further elements */            if (tempLeft==null && tempRight==null)                continue;             /* if only one is null---inequality, return false */            if ((tempLeft==null && tempRight!=null) ||                (tempLeft!=null && tempRight==null))                return false;             /* if both left and right nodes exist, but               have different values-- inequality,               return false*/            if (tempLeft.val != tempRight.val)                return false;             /* Note the order of insertion of elements               to the queue :               1) left child of left subtree               2) right child of right subtree               3) right child of left subtree               4) left child of right subtree */            q.add(tempLeft.left);            q.add(tempRight.right);            q.add(tempLeft.right);            q.add(tempRight.left);        }         /* if the flow reaches here, return true*/        return true;    }     /* driver function to test other functions */    public static void main(String[] args)    {        Node n = new Node(1);        BinaryTree bt = new BinaryTree(n);        bt.root.left = new Node(2);        bt.root.right = new Node(2);        bt.root.left.left = new Node(3);        bt.root.left.right = new Node(4);        bt.root.right.left = new Node(4);        bt.root.right.right = new Node(3);         if (bt.isSymmetric(bt.root))            System.out.println("The given tree is Symmetric");        else            System.out.println("The given tree is not Symmetric");    }}
# Python3 program to program to check if a# given Binary Tree is symmetric or not # Helper function that allocates a new# node with the given data and None# left and right pairs.                                    class newNode:     # Constructor to create a new node    def __init__(self, key):        self.key = key        self.left = None        self.right = None # function to check if a given# Binary Tree is symmetric or notdef isSymmetric( root) :     # if tree is empty    if (root == None) :        return True         # If it is a single tree node,    # then it is a symmetric tree.    if(not root.left and not root.right):        return True         q = []             # Add root to queue two times so that    # it can be checked if either one    # child alone is NULL or not.    q.append(root)    q.append(root)         # To store two nodes for checking    # their symmetry.    leftNode = 0    rightNode = 0         while(not len(q)):                 # Remove first two nodes to        # check their symmetry.        leftNode = q[0]        q.pop(0)                 rightNode = q[0]        q.pop(0)                 # if both left and right nodes        # exist, but have different        # values-. inequality, return False        if(leftNode.key != rightNode.key):            return False                 # append left child of left subtree        # node and right child of right         # subtree node in queue.        if(leftNode.left and rightNode.right) :            q.append(leftNode.left)            q.append(rightNode.right)                 # If only one child is present        # alone and other is NULL, then        # tree is not symmetric.        else if (leftNode.left or rightNode.right) :            return False                 # append right child of left subtree        # node and left child of right subtree        # node in queue.        if(leftNode.right and rightNode.left):            q.append(leftNode.right)            q.append(rightNode.left)                 # If only one child is present        # alone and other is NULL, then        # tree is not symmetric.        else if(leftNode.right or rightNode.left):            return False         return True         # Driver Codeif __name__ == '__main__':         # Let us construct the Tree    # shown in the above figure    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)) :        print("The given tree is Symmetric")    else:        print("The given tree is not Symmetric") # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// Iterative C# program to check if// given binary tree symmetricusing System;using System.Collections.Generic; public class BinaryTree{    public Node root;    public class Node    {        public int val;        public Node left, right;        public Node(int v)        {            val = v;            left = null;            right = null;        }    }     /* constructor to initialise the root */    BinaryTree(Node r) { root = r; }     /* empty constructor */    BinaryTree() { }      /* function to check if the tree is Symmetric */    public bool isSymmetric(Node root)    {        /* This allows adding null elements to the queue */        Queue<Node> q = new Queue<Node>();         /* Initially, add left and right nodes of root */        q.Enqueue(root.left);        q.Enqueue(root.right);         while (q.Count!=0)        {            /* remove the front 2 nodes to            check for equality */            Node tempLeft = q.Dequeue();            Node tempRight = q.Dequeue();             /* if both are null, continue and check            for further elements */            if (tempLeft==null && tempRight==null)                continue;             /* if only one is null---inequality, return false */            if ((tempLeft==null && tempRight!=null) ||                (tempLeft!=null && tempRight==null))                return false;             /* if both left and right nodes exist, but            have different values-- inequality,            return false*/            if (tempLeft.val != tempRight.val)                return false;             /* Note the order of insertion of elements            to the queue :            1) left child of left subtree            2) right child of right subtree            3) right child of left subtree            4) left child of right subtree */            q.Enqueue(tempLeft.left);            q.Enqueue(tempRight.right);            q.Enqueue(tempLeft.right);            q.Enqueue(tempRight.left);        }         /* if the flow reaches here, return true*/        return true;    }     /* driver code */    public static void Main(String[] args)    {        Node n = new Node(1);        BinaryTree bt = new BinaryTree(n);        bt.root.left = new Node(2);        bt.root.right = new Node(2);        bt.root.left.left = new Node(3);        bt.root.left.right = new Node(4);        bt.root.right.left = new Node(4);        bt.root.right.right = new Node(3);         if (bt.isSymmetric(bt.root))            Console.WriteLine("The given tree is Symmetric");        else            Console.WriteLine("The given tree is not Symmetric");    }} // This code is contributed by PrinciRaj1992
<script>  // Iterative Javascript program to check if// given binary tree symmetricvar root = null; class Node{    constructor(v)    {        this.val = v;        this.left = null;        this.right = null;    }} /* Function to check if the tree is Symmetric */function isSymmetric(root){         /* This allows adding null    elements to the queue */    var q = [];         /* Initially, add left and    right nodes of root */    q.push(root.left);    q.push(root.right);         while (q.length != 0)    {                 /* Remove the front 2 nodes to        check for equality */        var tempLeft = q[0];        q.shift();        var tempRight = q[0];        q.shift();                 /* If both are null, continue and check        for further elements */        if (tempLeft == null && tempRight == null)            continue;                     /* If only one is null---inequality, return false */        if ((tempLeft == null && tempRight != null) ||            (tempLeft != null && tempRight == null))            return false;                     /* If both left and right nodes exist, but        have different values-- inequality,        return false*/        if (tempLeft.val != tempRight.val)            return false;                     /* Note the order of insertion of elements        to the queue :        1) left child of left subtree        2) right child of right subtree        3) right child of left subtree        4) left child of right subtree */        q.push(tempLeft.left);        q.push(tempRight.right);        q.push(tempLeft.right);        q.push(tempRight.left);    }         /* If the flow reaches here, return true*/    return true;} // Driver codevar n = new Node(1);root = n;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))    document.write("The given tree is Symmetric");else    document.write("The given tree is not Symmetric"); // This code is contributed by noob2000 </script>
Output: 
The given tree is Symmetric
YouTubeGeeksforGeeks500K subscribersCheck for Symmetric Binary Tree (Iterative Approach) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:57•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=7yXBnlHZ0tY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nik1996
SHUBHAMSINGH10
princiraj1992
bhanuchand
noob2000
simranarora5sos
sooda367
simmytarika5
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
Decision Tree
Inorder Tree Traversal without recursion and without stack!
Construct Tree from given Inorder and Preorder traversals
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
Binary Tree (Array implementation)