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 tree elements at every level are palindromic. In example 2, at the leaf level, the elements are not palindromic.
In other words,
- The left child of left subtree = right child of right subtree.
- 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++
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int key;
struct Node* left, *right;
};
Node *newNode( int key)
{
Node *temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
bool isSymmetric( struct Node* root)
{
if (root == NULL)
return true ;
if (!root->left && !root->right)
return true ;
queue <Node*> q;
q.push(root);
q.push(root);
Node* leftNode, *rightNode;
while (!q.empty()){
leftNode = q.front();
q.pop();
rightNode = q.front();
q.pop();
if (leftNode->key != rightNode->key){
return false ;
}
if (leftNode->left && rightNode->right){
q.push(leftNode->left);
q.push(rightNode->right);
}
else if (leftNode->left || rightNode->right)
return false ;
if (leftNode->right && rightNode->left){
q.push(leftNode->right);
q.push(rightNode->left);
}
else if (leftNode->right || rightNode->left)
return false ;
}
return true ;
}
int main()
{
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;
}
|
Java
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 ;
}
}
BinaryTree(Node r) { root = r; }
BinaryTree() { }
public boolean isSymmetric(Node root)
{
Queue<Node> q = new LinkedList<Node>();
q.add(root.left);
q.add(root.right);
while (!q.isEmpty())
{
Node tempLeft = q.remove();
Node tempRight = q.remove();
if (tempLeft== null && tempRight== null )
continue ;
if ((tempLeft== null && tempRight!= null ) ||
(tempLeft!= null && tempRight== null ))
return false ;
if (tempLeft.val != tempRight.val)
return false ;
q.add(tempLeft.left);
q.add(tempRight.right);
q.add(tempLeft.right);
q.add(tempRight.left);
}
return true ;
}
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
class newNode:
def __init__( self , key):
self .key = key
self .left = None
self .right = None
def isSymmetric( root) :
if (root = = None ) :
return True
if ( not root.left and not root.right):
return True
q = []
q.append(root)
q.append(root)
leftNode = 0
rightNode = 0
while ( not len (q)):
leftNode = q[ 0 ]
q.pop( 0 )
rightNode = q[ 0 ]
q.pop( 0 )
if (leftNode.key ! = rightNode.key):
return False
if (leftNode.left and rightNode.right) :
q.append(leftNode.left)
q.append(rightNode.right)
elif (leftNode.left or rightNode.right) :
return False
if (leftNode.right and rightNode.left):
q.append(leftNode.right)
q.append(rightNode.left)
elif (leftNode.right or rightNode.left):
return False
return True
if __name__ = = '__main__' :
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" )
|
C#
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 ;
}
}
BinaryTree(Node r) { root = r; }
BinaryTree() { }
public bool isSymmetric(Node root)
{
Queue<Node> q = new Queue<Node>();
q.Enqueue(root.left);
q.Enqueue(root.right);
while (q.Count!=0)
{
Node tempLeft = q.Dequeue();
Node tempRight = q.Dequeue();
if (tempLeft== null && tempRight== null )
continue ;
if ((tempLeft== null && tempRight!= null ) ||
(tempLeft!= null && tempRight== null ))
return false ;
if (tempLeft.val != tempRight.val)
return false ;
q.Enqueue(tempLeft.left);
q.Enqueue(tempRight.right);
q.Enqueue(tempLeft.right);
q.Enqueue(tempRight.left);
}
return true ;
}
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" );
}
}
|
Javascript
<script>
var root = null ;
class Node
{
constructor(v)
{
this .val = v;
this .left = null ;
this .right = null ;
}
}
function isSymmetric(root)
{
var q = [];
q.push(root.left);
q.push(root.right);
while (q.length != 0)
{
var tempLeft = q[0];
q.shift();
var tempRight = q[0];
q.shift();
if (tempLeft == null && tempRight == null )
continue ;
if ((tempLeft == null && tempRight != null ) ||
(tempLeft != null && tempRight == null ))
return false ;
if (tempLeft.val != tempRight.val)
return false ;
q.push(tempLeft.left);
q.push(tempRight.right);
q.push(tempLeft.right);
q.push(tempRight.left);
}
return true ;
}
var 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" );
</script>
|
Output
The given tree is Symmetric
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(h), where h is the height of the tree.
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.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
16 Dec, 2022
Like Article
Save Article