The Wayback Machine - https://web.archive.org/web/20250306120658/https://www.geeksforgeeks.org/symmetric-tree-tree-which-is-mirror-image-of-itself/
Open In App

Symmetric Tree (Mirror Image of itself)

Last Updated : 21 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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

Example:

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 – 1] Using Recursion – O(n) Time and O(h) Space

The idea is to recursively compare the left and right subtrees of the root. For the tree to be symmetric, the root values of the left and right subtrees must match, and their corresponding children must also be mirrors.

C++
// C++ program to check if a given Binary
// Tree is symmetric

#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;

    Node(int val) {
        data = val;
        left = right = nullptr;
    }
};

// Recursive helper function to check if two subtrees are mirror images
bool isMirror(Node* leftSub, Node* rightSub) {
    
    // Both are null, so they are mirror images
    if (leftSub == nullptr && rightSub == nullptr) 
        return true;
    
    // One of them is null, so they aren't mirror images
    if (leftSub == nullptr || rightSub == nullptr || 
                    leftSub->data != rightSub->data) {
        return false;
    }
    
    // Check if the subtrees are mirrors
    return isMirror(leftSub->left, rightSub->right) &&
           isMirror(leftSub->right, rightSub->left);
}

bool isSymmetric(Node* root) {
    
    // If tree is empty, it's symmetric
    if (root == nullptr) 
        return true;
    
    // Check if the left and right subtrees are 
      // mirrors of each other
    return isMirror(root->left, root->right);
}

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;
}
C
// C program to check if a given Binary 
// Tree is symmetric

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct Node {
    int data;
    struct Node* left;
    struct Node* right;
} Node;

Node* createNode(int val) {
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = val;
    node->left = NULL;
    node->right = NULL;
    return node;
}

// Recursive helper function to check if two subtrees are mirror images
bool isMirror(Node* leftSub, Node* rightSub) {
  
    // Both are null, so they are mirror images
    if (leftSub == NULL && rightSub == NULL) 
        return true;
    
    // One of them is null, so they aren't mirror images
    if (leftSub == NULL || rightSub == NULL || leftSub->data != rightSub->data) 
        return false;

    // Check if the subtrees are mirrors
    return isMirror(leftSub->left, rightSub->right) && 
           isMirror(leftSub->right, rightSub->left);
}

bool isSymmetric(Node* root) {
    // If tree is empty, it's symmetric
    if (root == NULL) 
        return true;

    // Check if the left and right subtrees are mirrors of each other
    return isMirror(root->left, root->right);
}

int main() {
    // Creating a sample symmetric binary tree
    //        1
    //       / \
    //      2   2
    //     / \ / \
    //    3  4 4  3
    Node* root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(2);
    root->left->left = createNode(3);
    root->left->right = createNode(4);
    root->right->left = createNode(4);
    root->right->right = createNode(3);

    if (isSymmetric(root))
        printf("true\n");
    else
        printf("false\n");

    return 0;
}
Java
// Java program to check if a given 
// Binary Tree is symmetric

class Node {
    int data;
    Node left, right;

    Node(int val) {
        data = val;
        left = right = null;
    }
}

class GfG{

    // Recursive helper function to check if two subtrees are mirror images
    static boolean isMirror(Node leftSub, Node rightSub) {
      
        // Both are null, so they are mirror images
        if (leftSub == null && rightSub == null)
            return true;

        // One of them is null, so they aren't mirror images
        if (leftSub == null || rightSub == null 
                        || leftSub.data != rightSub.data)
            return false;

        // Check if the subtrees are mirrors
        return isMirror(leftSub.left, rightSub.right) && 
               isMirror(leftSub.right, rightSub.left);
    }

    static boolean isSymmetric(Node root) {
        // If tree is empty, it's symmetric
        if (root == null)
            return true;

        // Check if the left and right subtrees are mirrors of each other
        return isMirror(root.left, root.right);
    }

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

        if (isSymmetric(root))
            System.out.println("true");
        else
            System.out.println("false");
    }
}
Python
# Python program to check if a given 
# Binary Tree is symmetric

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

# Recursive helper function to check if two subtrees are mirror images
def isMirror(leftSub, rightSub):
  
    # Both are null, so they are mirror images
    if leftSub is None and rightSub is None:
        return True

    # One of them is null, so they aren't mirror images
    if leftSub is None or rightSub is None or leftSub.data != rightSub.data:
        return False
    
    # Check if the subtrees are mirrors
    return isMirror(leftSub.left, rightSub.right) and \
           isMirror(leftSub.right, rightSub.left)

def isSymmetric(root):
  
    # If tree is empty, it's symmetric
    if root is None:
        return True

    # Check if the left and right subtrees are mirrors of each other
    return isMirror(root.left, root.right)

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("true" if isSymmetric(root) else "false")
C#
// C# program to check if a given Binary 
// Tree is symmetric

using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int val) {
        data = val;
        left = right = null;
    }
}

class GfG {

    // Recursive helper function to check if two subtrees are mirror images
    static bool isMirror(Node leftSub, Node rightSub) {
      
        // Both are null, so they are mirror images
        if (leftSub == null && rightSub == null)
            return true;

        // One of them is null, so they aren't mirror images
        if (leftSub == null || rightSub == null || 
                        leftSub.data != rightSub.data)
            return false;

        // Check if the subtrees are mirrors
        return isMirror(leftSub.left, rightSub.right) && 
               isMirror(leftSub.right, rightSub.left);
    }

    static bool isSymmetric(Node root) {
      
        // If tree is empty, it's symmetric
        if (root == null)
            return true;

        // Check if the left and right subtrees are mirrors of each other
        return isMirror(root.left, root.right);
    }

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

        Console.WriteLine(isSymmetric(root) ? "true" : "false");
    }
}
JavaScript
// JavaScript program to check if a given 
// Binary Tree is symmetric

class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}

// Recursive helper function to check if two subtrees are mirror images
function isMirror(leftSub, rightSub) {
    // Both are null, so they are mirror images
    if (leftSub === null && rightSub === null) 
        return true;

    // One of them is null, so they aren't mirror images
    if (leftSub === null || rightSub === null || leftSub.data !== rightSub.data)
        return false;

    // Check if the subtrees are mirrors
    return isMirror(leftSub.left, rightSub.right) && 
           isMirror(leftSub.right, rightSub.left);
}

function isSymmetric(root) {
    // If tree is empty, it's symmetric
    if (root === null) 
        return true;

    // Check if the left and right subtrees are mirrors of each other
    return isMirror(root.left, root.right);
}

// Creating a sample symmetric binary tree
//        1
//       / \
//      2   2
//     / \ / \
//    3  4 4  3
const 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) ? "true" : "false");

Output
true

[Approach – 2] Using Stack – O(n) Time and O(h) Space

The idea is to use two stack to check if a binary tree is symmetric. One stack is for the left side of the tree, and the other is for the right side. By comparing nodes from both stack at each level, we can check if the left and right sides are mirror images of each other.

Step-by-step implementation:

  • Create a two stacks, say s1 and s2 and push the left child of the root node in s1 and right child of the root node into s2.
  • While both the stack are not empty, repeat the following steps:
    • Pop two nodes from the stack, say node1 and node2.
    • If both node1 and node2 are null, continue to the next iteration.
    • If one of the nodes is null and the other is not, return false as it is not a mirror.
    • If both nodes are not null, compare their values. If they are not equal, return false.
    • Push the left child of node1 and the right child of node2 onto the stack.
    • Push the right child of node1 and the left child of node2 onto the stack.
  • If the loop completes successfully without returning false, return true as it is a mirror.
C++
// C++ program to check if a given Binary
// Tree is symmetric

#include <iostream>
#include <stack>
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;

    // Two stacks to store nodes for comparison
    stack<Node*> s1, s2;

    // Initialize the stacks with the left 
      // and right subtrees
    s1.push(root->left);
    s2.push(root->right);

    while (!s1.empty() && !s2.empty()) {
        
        // Get the current pair of nodes
        Node* node1 = s1.top();
        Node* node2 = s2.top();
        s1.pop();
        s2.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;
        }

        // Push children of node1 and node2 in opposite order
        // Push left child of node1 and right child of node2
        s1.push(node1->left);
        s2.push(node2->right);

        // Push right child of node1 and left child of node2
        s1.push(node1->right);
        s2.push(node2->left);
    }

    // If both stacks are empty, the tree is symmetric
    return s1.empty() && s2.empty();
}

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.Stack;

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

        // Two stacks to store nodes for comparison
        Stack<Node> s1 = new Stack<>();
        Stack<Node> s2 = new Stack<>();

        // Initialize the stacks with the left
          // and right subtrees
        s1.push(root.left);
        s2.push(root.right);

        while (!s1.isEmpty() && !s2.isEmpty()) {

            // Get the current pair of nodes
            Node node1 = s1.pop();
            Node node2 = s2.pop();

            // 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;
            }

            // Push children of node1 and node2 in opposite order
            // Push left child of node1 and right child of node2
            s1.push(node1.left);
            s2.push(node2.right);

            // Push right child of node1 and left child of node2
            s1.push(node1.right);
            s2.push(node2.left);
        }

        // If both stacks are empty, the tree is symmetric
        return s1.isEmpty() && s2.isEmpty();
    }

    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

class Node:
    def __init__(self, val):
        self.data = val
        self.left = self.right = None

# Function to check if the binary tree is symmetric
def isSymmetric(root):
    if root is None:
        return True

    # Two stacks to store nodes for comparison
    s1 = []
    s2 = []

    # Initialize the stacks with the 
    # left and right subtrees
    s1.append(root.left)
    s2.append(root.right)

    while s1 and s2:
      
        # Get the current pair of nodes
        node1 = s1.pop()
        node2 = s2.pop()

        # 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

        # Push children of node1 and node2 in opposite order
        # Push left child of node1 and right child of node2
        s1.append(node1.left)
        s2.append(node2.right)

        # Push right child of node1 and left child of node2
        s1.append(node1.right)
        s2.append(node2.left)

    # If both stacks are empty, the tree is symmetric
    return len(s1) == 0 and len(s2) == 0

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

        // Two stacks to store nodes for comparison
        Stack<Node> s1 = new Stack<Node>();
        Stack<Node> s2 = new Stack<Node>();

        // Initialize the stacks with the left
          // and right subtrees
        s1.Push(root.left);
        s2.Push(root.right);

        while (s1.Count > 0 && s2.Count > 0) {
          
            // Get the current pair of nodes
            Node node1 = s1.Pop();
            Node node2 = s2.Pop();

            // 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;
            }

            // Push children of node1 and node2 in opposite order
            // Push left child of node1 and right child of node2
            s1.Push(node1.left);
            s2.Push(node2.right);

            // Push right child of node1 and left child of node2
            s1.Push(node1.right);
            s2.Push(node2.left);
        }

        // If both stacks are empty, the tree is symmetric
        return s1.Count == 0 && s2.Count == 0;
    }

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

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

    // Two stacks to store nodes for comparison
    let s1 = [];
    let s2 = [];

    // Initialize the stacks with the 
    // left and right subtrees
    s1.push(root.left);
    s2.push(root.right);

    while (s1.length > 0 && s2.length > 0) {
    
        // Get the current pair of nodes
        let node1 = s1.pop();
        let node2 = s2.pop();

        // 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;
        }

        // Push children of node1 and node2 in opposite order
        // Push left child of node1 and right child of node2
        s1.push(node1.left);
        s2.push(node2.right);

        // Push right child of node1 and left child of node2
        s1.push(node1.right);
        s2.push(node2.left);
    }

    // If both stacks are empty, the tree is symmetric
    return s1.length === 0 && s2.length === 0;
}

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

[Approach – 3] Using Queue – O(n) Time and O(n) Space

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. Please refer to Check for Symmetric Binary Tree (Iterative Approach Using Queue) for implementation.



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg