Symmetric Tree ( Mirror Image of itself ) | C ++ program to check if a given Binary Tree is symmetric or not ; A Binary Tree Node ; Utility function to create new Node ; Returns true if trees with roots as root1 and root2 are mirror ; If both trees are emptu , then they are mirror images ; 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 none of above conditions is true then root1 and root2 are not mirror images ; Returns true if a tree is symmetric i . e . mirror image of itself ; Check if tree is mirror of itself ; Driver code ; Let us construct the Tree shown in the above figure
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } bool isMirror ( struct Node * root1 , struct Node * root2 ) { if ( root1 == NULL && root2 == NULL ) return true ; if ( root1 && root2 && root1 -> key == root2 -> key ) return isMirror ( root1 -> left , root2 -> right ) && isMirror ( root1 -> right , root2 -> left ) ; return false ; } bool isSymmetric ( struct Node * root ) { return isMirror ( root , root ) ; } int main ( ) { 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 ; }