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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read