Open In App

Check for Symmetric Binary Tree (Iterative Approach Using Queue)

Last Updated : 26 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary tree, the task is to check whether it is a mirror of itself.

Examples: 

Input:

ex-1_1


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

Input:

ex-2_1

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));

Output
True

Time Complexity: O(n), where n is the number of nodes.
Space Complexity: O(n)

Related articles:



Next Article
Article Tags :
Practice Tags :

Similar Reads