Related Articles

# Check for Symmetric Binary Tree (Iterative Approach)

• Difficulty Level : Medium
• Last Updated : 28 Jun, 2021

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++

 `// C++ program to check if a given Binary``// Tree is symmetric or not``#include``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(``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 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 program``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 << ``"The given tree is Symmetric"``;``    ``else``        ``cout << ``"The given tree is not Symmetric"``;``    ``return` `0;``}` `// This code is contributed by Nikhil jindal.`

## Java

 `// Iterative Java program to check if``// given binary tree symmetric``import` `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 q = ``new` `LinkedList();` `        ``/* 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 chcek``               ``for further elements */``            ``if` `(tempLeft==``null` `&& tempRight==``null``)``                ``continue``;` `            ``/* if only one is null---inequality, retun 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

 `# 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 not``def` `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.``        ``elif` `(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.``        ``elif``(leftNode.right ``or` `rightNode.left):``            ``return` `False``    ` `    ``return` `True``        ` `# Driver Code``if` `__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)`

## C#

 `// Iterative C# program to check if``// given binary tree symmetric``using` `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 q = ``new` `Queue();` `        ``/* 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 chcek``            ``for further elements */``            ``if` `(tempLeft==``null` `&& tempRight==``null``)``                ``continue``;` `            ``/* if only one is null---inequality, retun 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`

## Javascript

 ``

Output:

`The given tree is Symmetric`

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.