Check for Symmetric Binary Tree (Iterative Approach Using Queue)
Last Updated :
26 Sep, 2024
Given a binary tree, the task is to check whether it is a mirror of itself.
Examples:
Input:

Output: True
Explanation: As the left and right half of the above tree is mirror image, tree is symmetric.
Input:

Output: False
Explanation: As the left and right half of the above tree is not the mirror image, tree is not symmetric.
Approach:
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. Initially, we push the root node into the queue twice. 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 below to solve the problem:
- If the root node is NULL, return true as an empty binary tree is considered symmetric.
- Create a queue and push the left and right child of root node into the queue.
- While the queue is not empty, dequeue two nodes at a time, one for the left subtree and one for the right subtree.
- If both the left and right nodes are NULL, continue to the next iteration as the subtrees are considered mirror images of each other.
- 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.
- 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.
- 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++ program to check if a given Binary
// Tree is symmetric
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int val) {
data = val;
left = right = nullptr;
}
};
// Function to check if the binary tree is symmetric
bool isSymmetric(Node* root) {
if (root == nullptr) {
return true;
}
// Use a queue to store nodes for comparison
queue<Node*> q;
// Initialize the queue with the left
// and right subtrees
q.push(root->left);
q.push(root->right);
while (!q.empty()) {
Node* node1 = q.front();
q.pop();
Node* node2 = q.front();
q.pop();
// If both nodes are null, continue to the next pair
if (node1 == nullptr && node2 == nullptr) {
continue;
}
// If one node is null and the other is not,
// or the nodes' data do not match
// then the tree is not symmetric
if (node1 == nullptr || node2 == nullptr ||
node1->data != node2->data) {
return false;
}
// Enqueue children in opposite
// order to compare them
q.push(node1->left);
q.push(node2->right);
q.push(node1->right);
q.push(node2->left);
}
// If the loop completes without
// returning false, the tree is symmetric
return true;
}
int main() {
// Creating a sample symmetric binary tree
// 1
// / \
// 2 2
// / \ / \
// 3 4 4 3
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)) {
cout << "True";
}
else cout << "False";
return 0;
}
Java
// Java program to check if a given
// Binary Tree is symmetric
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
Node(int val) {
data = val;
left = right = null;
}
}
class GfG {
// Function to check if the binary tree is symmetric
static boolean isSymmetric(Node root) {
if (root == null) {
return true;
}
// Use a queue to store nodes for comparison
Queue<Node> q = new LinkedList<>();
// Initialize the queue with the left and right subtrees
q.offer(root.left);
q.offer(root.right);
while (!q.isEmpty()) {
Node node1 = q.poll();
Node node2 = q.poll();
// If both nodes are null, continue to the next pair
if (node1 == null && node2 == null) {
continue;
}
// If one node is null and the other is not,
// or the nodes' data do not match
// then the tree is not symmetric
if (node1 == null || node2 == null ||
node1.data != node2.data) {
return false;
}
// Enqueue children in opposite order to compare them
q.offer(node1.left);
q.offer(node2.right);
q.offer(node1.right);
q.offer(node2.left);
}
// If the loop completes without
// returning false, the tree is symmetric
return true;
}
public static void main(String[] args) {
// Creating a sample symmetric binary tree
// 1
// / \
// 2 2
// / \ / \
// 3 4 4 3
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);
System.out.println(isSymmetric(root));
}
}
Python
# Python program to check if a given
# Binary Tree is symmetric
from collections import deque
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
# Function to check if the binary
# tree is symmetric
def isSymmetric(root):
if root is None:
return True
# Use a queue to store nodes for comparison
q = deque()
# Initialize the queue with the left
# and right subtrees
q.append(root.left)
q.append(root.right)
while q:
node1 = q.popleft()
node2 = q.popleft()
# If both nodes are null, continue to the next pair
if node1 is None and node2 is None:
continue
# If one node is null and the other is not,
# or the nodes' data do not match
# then the tree is not symmetric
if node1 is None or node2 \
is None or node1.data != node2.data:
return False
# Enqueue children in opposite order
# to compare them
q.append(node1.left)
q.append(node2.right)
q.append(node1.right)
q.append(node2.left)
# If the loop completes without
# returning false, the tree is symmetric
return True
if __name__ == "__main__":
# Creating a sample symmetric binary tree
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
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(isSymmetric(root))
C#
// C# program to check if a given Binary
// Tree is symmetric
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int val) {
data = val;
left = right = null;
}
}
class GfG {
// Function to check if the binary tree is symmetric
static bool IsSymmetric(Node root) {
if (root == null) {
return true;
}
// Use a queue to store nodes for comparison
Queue<Node> q = new Queue<Node>();
// Initialize the queue with the
// left and right subtrees
q.Enqueue(root.left);
q.Enqueue(root.right);
while (q.Count > 0) {
Node node1 = q.Dequeue();
Node node2 = q.Dequeue();
// If both nodes are null,
// continue to the next pair
if (node1 == null && node2 == null) {
continue;
}
// If one node is null and the other is not,
// or the nodes' data do not match
// then the tree is not symmetric
if (node1 == null || node2 == null ||
node1.data != node2.data) {
return false;
}
// Enqueue children in opposite
// order to compare them
q.Enqueue(node1.left);
q.Enqueue(node2.right);
q.Enqueue(node1.right);
q.Enqueue(node2.left);
}
// If the loop completes without
// returning false, the tree is symmetric
return true;
}
static void Main() {
// Creating a sample symmetric binary tree
// 1
// / \
// 2 2
// / \ / \
// 3 4 4 3
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);
Console.WriteLine(IsSymmetric(root));
}
}
JavaScript
// JavaScript program to check if a given
// Binary Tree is symmetric
class Node {
constructor(val) {
this.data = val;
this.left = this.right = null;
}
}
// Function to check if the binary tree is symmetric
function isSymmetric(root) {
if (root === null) {
return true;
}
// Use a queue to store nodes for comparison
const q = [];
// Initialize the queue with the left
// and right subtrees
q.push(root.left);
q.push(root.right);
while (q.length > 0) {
const node1 = q.shift();
const node2 = q.shift();
// If both nodes are null,
// continue to the next pair
if (node1 === null && node2 === null) {
continue;
}
// If one node is null and the other is not,
// or the nodes' data do not match
// then the tree is not symmetric
if (node1 === null || node2 === null ||
node1.data !== node2.data) {
return false;
}
// Enqueue children in opposite
// order to compare them
q.push(node1.left);
q.push(node2.right);
q.push(node1.right);
q.push(node2.left);
}
// If the loop completes without
// returning false, the tree is symmetric
return true;
}
// Creating a sample symmetric binary tree
// 1
// / \
// 2 2
// / \ / \
// 3 4 4 3
let 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);
console.log(isSymmetric(root));
Time Complexity: O(n), where n is the number of nodes.
Space Complexity: O(n)
Related articles:
Similar Reads
Iterative approach to check if a Binary Tree is Perfect Given a Binary Tree, the task is to check whether the given Binary Tree is a perfect Binary Tree or not.A Binary tree is a Perfect Binary Tree in which all internal nodes have two children and all leaves are at the same level.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : Yes Input : 20 / \ 8
9 min read
Iterative approach to check for children sum property in a Binary Tree Given a binary tree, write a function that returns true if the tree satisfies below property:For every node, data value must be equal to the sum of data values in left and right children. Consider data value as 0 for NULL children.Examples: Input : 10 / \ 8 2 / \ \ 3 5 2 Output : Yes Input : 5 / \ -
8 min read
Iterative approach to check if a Binary Tree is BST or not Given a Binary Tree, the task is to check if the given binary tree is a Binary Search Tree or not. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: 9 / \ 6 10 / \ \ 4 7 11 / \ \ 3 5 8 Output: YES Explanation: Since the left subtree of each node of the tree consists of s
9 min read
Iterative Search for a key 'x' in Binary Tree Given a Binary Tree and a key to be searched in it, write an iterative method that returns true if key is present in Binary Tree, else false. For example, in the following tree, if the searched key is 3, then function should return true and if the searched key is 12, then function should return fals
14 min read
Iterative Approach to check if two Binary Trees are Isomorphic or not Given two Binary Trees, the task is to check whether they are isomorphic or not. Two trees are called isomorphic if one of them can be obtained from the other by a series of flips, i.e. by swapping left and right children of several nodes. Any number of nodes at any level can have their children swa
11 min read