Open in App
Not now

# Symmetric Tree (Mirror Image of itself)

• Difficulty Level : Medium
• Last Updated : 24 Mar, 2023

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

For example, this binary tree is symmetric:

```     1
/   \
2     2
/ \   / \
3   4 4   3

But the following is not:
1
/ \
2   2
\   \
3    3```
Recommended Practice

The idea is to write a recursive function isMirror() that takes two trees as an argument and returns true if trees are the mirror and false if trees are not mirrored. The isMirror() function recursively checks two roots and subtrees under the root.

Below is the implementation of the above algorithm.

## C++14

 `// C++ program to check if a given Binary Tree is symmetric` `// or not` `#include ` `using` `namespace` `std;`   `// A Binary Tree Node` `struct` `Node {` `    ``int` `key;` `    ``struct` `Node *left, *right;` `};`   `// Utility function to create new Node` `Node* newNode(``int` `key)` `{` `    ``Node* temp = ``new` `Node;` `    ``temp->key = key;` `    ``temp->left = temp->right = NULL;` `    ``return` `(temp);` `}`   `// Returns true if trees with roots as root1 and root2 are` `// mirror` `bool` `isMirror(``struct` `Node* root1, ``struct` `Node* root2)` `{` `    ``// If both trees are empty, then they are mirror images` `    ``if` `(root1 == NULL && root2 == NULL)` `        ``return` `true``;`   `    ``// For two trees to be mirror images, the following` `    ``// three conditions must be true` `    ``// 1.) Their root node's key must be same` `    ``// 2.) left subtree of left tree and right subtree of` `    ``// right tree have to be mirror images` `    ``// 3.) right subtree of left tree and left subtree of` `    ``// right tree have to be mirror images` `    ``if` `(root1 && root2 && root1->key == root2->key)` `        ``return` `isMirror(root1->left, root2->right)` `               ``&& isMirror(root1->right, root2->left);`   `    ``// if none of above conditions is true then root1` `    ``// and root2 are not mirror images` `    ``return` `false``;` `}`   `// Returns true if a tree is symmetric i.e. mirror image of itself` `bool` `isSymmetric(``struct` `Node* root)` `{` `    ``// Check if tree is mirror of itself` `    ``return` `isMirror(root, root);` `}`   `// Driver code` `int` `main()` `{` `    ``// Let us construct the Tree shown in the above figure` `    ``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 << ``"Symmetric"``;` `    ``else` `        ``cout << ``"Not symmetric"``;` `    ``return` `0;` `}`   `// This code is contributed by Sania Kumari Gupta`

## C

 `// C program to check if a given Binary Tree is symmetric` `// or not` `#include ` `#include ` `#include `   `// A Binary Tree Node` `typedef` `struct` `Node {` `    ``int` `key;` `    ``struct` `Node *left, *right;` `} Node;`   `// Utility function to create new Node` `Node* newNode(``int` `key)` `{` `    ``Node* temp = (Node *)``malloc``(``sizeof``(Node));` `    ``temp->key = key;` `    ``temp->left = temp->right = NULL;` `    ``return` `(temp);` `}`   `// Returns true if trees with roots as root1 and root2 are` `// mirror` `bool` `isMirror(Node* root1, Node* root2)` `{` `    ``// If both trees are empty, then they are mirror images` `    ``if` `(root1 == NULL && root2 == NULL)` `        ``return` `true``;`   `    ``// For two trees to be mirror images, the following` `    ``// three conditions must be true` `    ``// 1.) Their root node's key must be same` `    ``// 2.) left subtree of left tree and right subtree of` `    ``// right tree have to be mirror images` `    ``// 3.) right subtree of left tree and left subtree of` `    ``// right tree have to be mirror images` `    ``if` `(root1 && root2 && root1->key == root2->key)` `        ``return` `isMirror(root1->left, root2->right)` `               ``&& isMirror(root1->right, root2->left);`   `    ``// if none of above conditions is true then root1` `    ``// and root2 are not mirror images` `    ``return` `false``;` `}`   `// Returns true if a tree is symmetric i.e. mirror image of` `// itself` `bool` `isSymmetric(Node* root)` `{` `    ``// Check if tree is mirror of itself` `    ``return` `isMirror(root, root);` `}`   `// Driver code` `int` `main()` `{` `    ``// Let us construct the Tree shown in the above figure` `    ``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))` `        ``printf``(``"Symmetric"``);` `    ``else` `        ``printf``(``"Not symmetric"``);` `    ``return` `0;` `}`   `// This code is contributed by Sania Kumari Gupta`

## Java

 `// Java program to check is binary tree is symmetric or not` `class` `Node {` `    ``int` `key;` `    ``Node left, right;` `    ``Node(``int` `item)` `    ``{` `        ``key = item;` `        ``left = right = ``null``;` `    ``}` `}`   `class` `BinaryTree {` `    ``Node root;`   `    ``// returns true if trees with roots as root1 and` `    ``// root2 are mirror` `    ``boolean` `isMirror(Node node1, Node node2)` `    ``{` `        ``// if both trees are empty, then they are mirror image` `        ``if` `(node1 == ``null` `&& node2 == ``null``)` `            ``return` `true``;`   `        ``// For two trees to be mirror images, the following` `        ``// three conditions must be true` `        ``// 1.) Their root node's key must be same` `        ``// 2.) left subtree of left tree and right subtree` `        ``// of right tree have to be mirror images` `        ``// 3.) right subtree of left tree and left subtree` `        ``// of right tree have to be mirror images` `        ``if` `(node1 != ``null` `&& node2 != ``null` `            ``&& node1.key == node2.key)` `            ``return` `(isMirror(node1.left, node2.right)` `                    ``&& isMirror(node1.right, node2.left));`   `        ``// if none of the above conditions is true then` `        ``// root1 and root2 are not mirror images` `        ``return` `false``;` `    ``}`   `    ``// returns true if the tree is symmetric i.e` `    ``// mirror image of itself` `    ``boolean` `isSymmetric()` `    ``{` `        ``// check if tree is mirror of itself` `        ``return` `isMirror(root, root);` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``BinaryTree tree = ``new` `BinaryTree();` `        ``tree.root = ``new` `Node(``1``);` `        ``tree.root.left = ``new` `Node(``2``);` `        ``tree.root.right = ``new` `Node(``2``);` `        ``tree.root.left.left = ``new` `Node(``3``);` `        ``tree.root.left.right = ``new` `Node(``4``);` `        ``tree.root.right.left = ``new` `Node(``4``);` `        ``tree.root.right.right = ``new` `Node(``3``);` `        ``boolean` `output = tree.isSymmetric();` `        ``if` `(output == ``true``)` `            ``System.out.println(``"Symmetric"``);` `        ``else` `            ``System.out.println(``"Not symmetric"``);` `    ``}` `}`   `// This code is contributed by Sania Kumari Gupta`

## Python3

 `# Python program to check if a ` `# given Binary Tree is symmetric or not`   `# Node structure`     `class` `Node:`   `    ``# Utility function to create new node` `    ``def` `__init__(``self``, key):` `        ``self``.key ``=` `key` `        ``self``.left ``=` `None` `        ``self``.right ``=` `None`   `# Returns True if trees ` `#with roots as root1 and root 2  are mirror`     `def` `isMirror(root1, root2):` `    ``# If both trees are empty, then they are mirror images` `    ``if` `root1 ``is` `None` `and` `root2 ``is` `None``:` `        ``return` `True`   `    ``""" For two trees to be mirror images, ` `        ``the following three conditions must be true` `        ``1 - Their root node's key must be same` `        ``2 - left subtree of left tree and right subtree` `          ``of the right tree have to be mirror images` `        ``3 - right subtree of left tree and left subtree` `           ``of right tree have to be mirror images` `    ``"""` `    ``if` `(root1 ``is` `not` `None` `and` `root2 ``is` `not` `None``):` `        ``if` `root1.key ``=``=` `root2.key:` `            ``return` `(isMirror(root1.left, root2.right)``and` `                    ``isMirror(root1.right, root2.left))`   `    ``# If none of the above conditions is true then root1` `    ``# and root2 are not mirror images` `    ``return` `False`     `def` `isSymmetric(root):`   `    ``# Check if tree is mirror of itself` `    ``return` `isMirror(root, root)`     `# Driver Code` `# Let's construct the tree show in the above figure` `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` `(``"Symmetric"` `if` `isSymmetric(root) ``=``=` `True` `else` `"Not symmetric"``)`   `# This code is contributed by Nikhil Kumar Singh(nickzuck_007)`

## C#

 `// C# program to check is binary` `// tree is symmetric or not` `using` `System;`   `class` `Node {` `    ``public` `int` `key;` `    ``public` `Node left, right;`   `    ``public` `Node(``int` `item)` `    ``{` `        ``key = item;` `        ``left = right = ``null``;` `    ``}` `}`   `class` `GFG {` `    ``Node root;`   `    ``// returns true if trees with roots` `    ``// as root1 and root2 are mirror` `    ``Boolean isMirror(Node node1, Node node2)` `    ``{` `        ``// if both trees are empty,` `        ``// then they are mirror image` `        ``if` `(node1 == ``null` `&& node2 == ``null``)` `            ``return` `true``;`   `        ``// For two trees to be mirror images,` `        ``// the following three conditions must be true` `        ``// 1 - Their root node's key must be same` `        ``// 2 - left subtree of left tree and right ` `        ``// subtree of right tree have to be mirror images` `        ``// 3 - right subtree of left tree and left subtree` `        ``// of right tree have to be mirror images` `        ``if` `(node1 != ``null` `&& node2 != ``null` `            ``&& node1.key == node2.key)` `            ``return` `(isMirror(node1.left, node2.right)` `                    ``&& isMirror(node1.right, node2.left));`   `        ``// if none of the above conditions` `        ``// is true then root1 and root2 are` `        ``// mirror images` `        ``return` `false``;` `    ``}`   `    ``// returns true if the tree is symmetric` `    ``// i.e mirror image of itself` `    ``Boolean isSymmetric()` `    ``{` `        ``// check if tree is mirror of itself` `        ``return` `isMirror(root, root);` `    ``}`   `    ``// Driver Code` `    ``static` `public` `void` `Main(String[] args)` `    ``{` `        ``GFG tree = ``new` `GFG();` `        ``tree.root = ``new` `Node(1);` `        ``tree.root.left = ``new` `Node(2);` `        ``tree.root.right = ``new` `Node(2);` `        ``tree.root.left.left = ``new` `Node(3);` `        ``tree.root.left.right = ``new` `Node(4);` `        ``tree.root.right.left = ``new` `Node(4);` `        ``tree.root.right.right = ``new` `Node(3);` `        ``Boolean output = tree.isSymmetric();` `        ``if` `(output == ``true``)` `            ``Console.WriteLine(``"Symmetric"``);` `        ``else` `            ``Console.WriteLine(``"Not symmetric"``);` `    ``}` `}`   `// This code is contributed by Arnab Kundu`

## Javascript

 ``

Output

`Symmetric`

Time Complexity: O(N)
Auxiliary Space: O(h) where h is the maximum height of the tree

Iterative Approach:

Algorithm for checking whether a binary tree is a mirror of itself using an iterative approach and a stack:

1. Create a stack and push the root node onto it twice.
2. While the stack is not empty, repeat the following steps:
a. Pop two nodes from the stack, say node1 and node2.
b. If both node1 and node2 are null, continue to the next iteration.
c. If one of the nodes is null and the other is not, return false as it is not a mirror.
d. If both nodes are not null, compare their values. If they are not equal, return false.
e. Push the left child of node1 and the right child of node2 onto the stack.
f. Push the right child of node1 and the left child of node2 onto the stack.
3. 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` `// or not` `#include ` `using` `namespace` `std;`   `// A Binary Tree Node` `struct` `Node {` `    ``int` `key;` `    ``struct` `Node *left, *right;` `};`   `// Utility function to create new Node` `Node* newNode(``int` `key)` `{` `    ``Node* temp = ``new` `Node;` `    ``temp->key = key;` `    ``temp->left = temp->right = NULL;` `    ``return` `(temp);` `}`   `// Returns true if a tree is symmetric i.e. mirror image of` `// itself` `bool` `isSymmetric(Node* root){` `    ``// If the root is null, then the binary tree is` `    ``// symmetric.` `    ``if` `(root == NULL) {` `        ``return` `true``;` `    ``}`   `    ``// Create a stack to store the left and right subtrees` `    ``// of the root.` `    ``stack stack;` `    ``stack.push(root->left);` `    ``stack.push(root->right);`   `    ``// Continue the loop until the stack is empty.` `    ``while` `(!stack.empty()) {` `        ``// Pop the left and right subtrees from the stack.` `        ``Node* node1 = stack.top();` `          ``stack.pop();` `        ``Node* node2 = stack.top();` `          ``stack.pop();`   `        ``// If both nodes are null, continue the loop.` `        ``if` `(node1 == NULL && node2 == NULL) {` `            ``continue``;` `        ``}`   `        ``// If one of the nodes is null, the binary tree is` `        ``// not symmetric.` `        ``if` `(node1 == NULL || node2 == NULL) {` `            ``return` `false``;` `        ``}`   `        ``// If the values of the nodes are not equal, the` `        ``// binary tree is not symmetric.` `        ``if` `(node1->key != node2->key) {` `            ``return` `false``;` `        ``}`   `        ``// Push the left and right subtrees of the left and` `        ``// right nodes onto the stack in the opposite order.` `        ``stack.push(node1->left);` `        ``stack.push(node2->right);` `        ``stack.push(node1->right);` `        ``stack.push(node2->left);` `    ``}`   `    ``// If the loop completes, the binary tree is symmetric.` `    ``return` `true``;` `}`   `// Driver code` `int` `main()` `{` `    ``// Let us construct the Tree shown in the above figure` `    ``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 << ``"Symmetric"``;` `    ``else` `        ``cout << ``"Not symmetric"``;` `    ``return` `0;` `}`   `// This code is contributed by sramshyam`

## Python3

 `class` `Node:` `    ``def` `__init__(``self``, key):` `        ``self``.key ``=` `key` `        ``self``.left ``=` `None` `        ``self``.right ``=` `None`   `def` `isSymmetric(root):` `    ``# If the root is null, then the binary tree is symmetric` `    ``if` `not` `root:` `        ``return` `True` `    `  `    ``# Create a stack to store the left and right subtrees of the root` `    ``stack ``=` `[]` `    ``stack.append(root.left)` `    ``stack.append(root.right)` `    `  `    ``# Continue the loop until the stack is empty` `    ``while` `stack:` `        ``# Pop the left and right subtrees from the stack` `        ``node1 ``=` `stack.pop()` `        ``node2 ``=` `stack.pop()` `        `  `        ``# If both nodes are null, continue the loop` `        ``if` `not` `node1 ``and` `not` `node2:` `            ``continue` `        `  `        ``# If one of the nodes is null, the binary tree is not symmetric` `        ``if` `not` `node1 ``or` `not` `node2:` `            ``return` `False` `        `  `        ``# If the values of the nodes are not equal, the binary tree is not symmetric` `        ``if` `node1.key !``=` `node2.key:` `            ``return` `False` `        `  `        ``# Push the left and right subtrees of the left and right nodes onto the stack in the opposite order` `        ``stack.append(node1.left)` `        ``stack.append(node2.right)` `        ``stack.append(node1.right)` `        ``stack.append(node2.left)` `    `  `    ``# If the loop completes, the binary tree is symmetric` `    ``return` `True`   `# Driver code` `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``)`   `if` `isSymmetric(root):` `    ``print``(``"Symmetric"``)` `else``:` `    ``print``(``"Not symmetric"``)`

Output

`Symmetric`

Time Complexity: O(n) where n is the number of nodes.
Space Complexity: O(h) where h is the height of the tree.

My Personal Notes arrow_drop_up
Related Articles