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++
#include<iostream>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left,*right;Node(intval){data=val;left=right=nullptr;}};// Recursive helper function to// check if two subtrees are mirror imagesboolisMirror(Node*leftSub,Node*rightSub){if(leftSub==nullptr&&rightSub==nullptr)returntrue;// One of them is null, so they aren't mirror imagesif(leftSub==nullptr||rightSub==nullptr||leftSub->data!=rightSub->data){returnfalse;}// Check if the subtrees are mirrorsreturnisMirror(leftSub->left,rightSub->right)&&isMirror(leftSub->right,rightSub->left);}boolisSymmetric(Node*root){if(root==nullptr)returntrue;returnisMirror(root->left,root->right);}intmain(){// Creating a sample symmetric binary tree// 10// / \ // 5 5// / \ // 2 2Node*root=newNode(10);root->left=newNode(5);root->right=newNode(5);root->left->left=newNode(2);root->right->right=newNode(2);if(isSymmetric(root))cout<<"true";elsecout<<"false";return0;}
Java
// Node StructureclassNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}classGFG{// Recursive helper function to// check if two subtrees are mirror imagesstaticbooleanisMirror(NodeleftSub,NoderightSub){if(leftSub==null&&rightSub==null)returntrue;// One of them is null, so they aren't mirror imagesif(leftSub==null||rightSub==null||leftSub.data!=rightSub.data)returnfalse;// Check if the subtrees are mirrorsreturnisMirror(leftSub.left,rightSub.right)&&isMirror(leftSub.right,rightSub.left);}staticbooleanisSymmetric(Noderoot){if(root==null)returntrue;returnisMirror(root.left,root.right);}publicstaticvoidmain(String[]args){// Creating a sample symmetric binary tree// 10// / \// 5 5// / \// 2 2Noderoot=newNode(10);root.left=newNode(5);root.right=newNode(5);root.left.left=newNode(2);root.right.right=newNode(2);if(isSymmetric(root))System.out.println("true");elseSystem.out.println("false");}}
Python
# Node StructureclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Recursive helper function to check #if two subtrees are mirror imagesdefisMirror(leftSub,rightSub):ifleftSubisNoneandrightSubisNone:returnTrue# One of them is null, so they aren't mirror imagesifleftSubisNoneorrightSubisNoneorleftSub.data!=rightSub.data:returnFalse# Check if the subtrees are mirrorsreturnisMirror(leftSub.left,rightSub.right)and \
isMirror(leftSub.right,rightSub.left)defisSymmetric(root):ifrootisNone:returnTruereturnisMirror(root.left,root.right)if__name__=="__main__":# Creating a sample symmetric binary tree# 10# / \# 5 5# / \# 2 2root=Node(10)root.left=Node(5)root.right=Node(5)root.left.left=Node(2)root.right.right=Node(2)print("true"ifisSymmetric(root)else"false")
C#
usingSystem;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classGFG{// Recursive helper function// to check if two subtrees are mirror imagesstaticboolisMirror(NodeleftSub,NoderightSub){if(leftSub==null&&rightSub==null)returntrue;// One of them is null, so they aren't mirror imagesif(leftSub==null||rightSub==null||leftSub.data!=rightSub.data)returnfalse;// Check if the subtrees are mirrorsreturnisMirror(leftSub.left,rightSub.right)&&isMirror(leftSub.right,rightSub.left);}staticboolisSymmetric(Noderoot){if(root==null)returntrue;returnisMirror(root.left,root.right);}staticvoidMain(string[]args){// Creating a sample symmetric binary tree// 10// / \// 5 5// / \// 2 2Noderoot=newNode(10);root.left=newNode(5);root.right=newNode(5);root.left.left=newNode(2);root.right.right=newNode(2);Console.WriteLine(isSymmetric(root)?"true":"false");}}
JavaScript
// Node StructureclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Recursive helper function to// check if two subtrees are mirror imagesfunctionisMirror(leftSub,rightSub){if(leftSub===null&&rightSub===null)returntrue;// One of them is null, so they aren't mirror imagesif(leftSub===null||rightSub===null||leftSub.data!==rightSub.data)returnfalse;// Check if the subtrees are mirrorsreturnisMirror(leftSub.left,rightSub.right)&&isMirror(leftSub.right,rightSub.left);}functionisSymmetric(root){if(root===null)returntrue;returnisMirror(root.left,root.right);}// Driver Code// Creating a sample symmetric binary tree// 10// / \// 5 5// / \// 2 2letroot=newNode(10);root.left=newNode(5);root.right=newNode(5);root.left.left=newNode(2);root.right.right=newNode(2);console.log(isSymmetric(root)?"true":"false");
Output
true
Time Complexity: O(n) Auxiliary Space: O(h), where h is height of binary tree due to recursive stack space
[Approach - 2] Using Stack - O(n) Time and O(n) Space
We can use two stacks to check for symmetry of binary tree: one for the left subtree and one for the right. At each step, nodes are popped and compared; if they differ, the tree is not symmetric. Their children are then pushed in mirror order to ensure proper matching.
C++
#include<iostream>#include<stack>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left,*right;Node(intval){data=val;left=right=nullptr;}};boolisSymmetric(Node*root){if(root==nullptr)returntrue;stack<Node*>s1,s2;// Initialize the stacks with the left // and right subtreess1.push(root->left);s2.push(root->right);while(!s1.empty()&&!s2.empty()){// Get the current pair of nodesNode*node1=s1.top();Node*node2=s2.top();s1.pop();s2.pop();// If both nodes are null, continue to the next pairif(node1==nullptr&&node2==nullptr){continue;}if(node1==nullptr||node2==nullptr||node1->data!=node2->data){returnfalse;}// Push children of node1 and node2 in opposite order// Push left child of node1 and right child of node2s1.push(node1->left);s2.push(node2->right);// Push right child of node1 and left child of node2s1.push(node1->right);s2.push(node2->left);}returns1.empty()&&s2.empty();}intmain(){// Creating a sample symmetric binary tree// 10// / \ // 5 5// / \ // 2 2Node*root=newNode(10);root->left=newNode(5);root->right=newNode(5);root->left->left=newNode(2);root->right->right=newNode(2);if(isSymmetric(root))cout<<"true";elsecout<<"false";return0;}
Java
importjava.util.Stack;// Node StructureclassNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}classGFG{staticbooleanisSymmetric(Noderoot){if(root==null){returntrue;}Stack<Node>s1=newStack<>();Stack<Node>s2=newStack<>();// Initialize the stacks with the left// and right subtreess1.push(root.left);s2.push(root.right);while(!s1.isEmpty()&&!s2.isEmpty()){// Get the current pair of nodesNodenode1=s1.pop();Nodenode2=s2.pop();// If both nodes are null, continue to the next pairif(node1==null&&node2==null){continue;}if(node1==null||node2==null||node1.data!=node2.data){returnfalse;}// Push children of node1 and node2 in opposite order// Push left child of node1 and right child of node2s1.push(node1.left);s2.push(node2.right);// Push right child of node1 and left child of node2s1.push(node1.right);s2.push(node2.left);}returns1.isEmpty()&&s2.isEmpty();}publicstaticvoidmain(String[]args){// Creating a sample symmetric binary tree// 10// / \// 5 5// / \// 2 2Noderoot=newNode(10);root.left=newNode(5);root.right=newNode(5);root.left.left=newNode(2);root.right.right=newNode(2);System.out.println(isSymmetric(root));}}
Python
# Node StructureclassNode:def__init__(self,val):self.data=valself.left=self.right=NonedefisSymmetric(root):ifrootisNone:returnTrues1=[]s2=[]# Initialize the stacks with the # left and right subtreess1.append(root.left)s2.append(root.right)whiles1ands2:# Get the current pair of nodesnode1=s1.pop()node2=s2.pop()# If both nodes are null, continue to the next pairifnode1isNoneandnode2isNone:continueifnode1isNoneornode2isNoneornode1.data!=node2.data:returnFalse# Push children of node1 and node2 in opposite order# Push left child of node1 and right child of node2s1.append(node1.left)s2.append(node2.right)# Push right child of node1 and left child of node2s1.append(node1.right)s2.append(node2.left)returnlen(s1)==0andlen(s2)==0if__name__=="__main__":# Creating a sample symmetric binary tree# 10# / \# 5 5# / \# 2 2root=Node(10)root.left=Node(5)root.right=Node(5)root.left.left=Node(2)root.right.right=Node(2)print("true"ifisSymmetric(root)else"false")
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classGFG{staticboolisSymmetric(Noderoot){if(root==null){returntrue;}Stack<Node>s1=newStack<Node>();Stack<Node>s2=newStack<Node>();// Initialize the stacks with the left// and right subtreess1.Push(root.left);s2.Push(root.right);while(s1.Count>0&&s2.Count>0){// Get the current pair of nodesNodenode1=s1.Pop();Nodenode2=s2.Pop();// If both nodes are null, continue to the next pairif(node1==null&&node2==null){continue;}if(node1==null||node2==null||node1.data!=node2.data){returnfalse;}// Push children of node1 and node2 in opposite order// Push left child of node1 and right child of node2s1.Push(node1.left);s2.Push(node2.right);// Push right child of node1 and left child of node2s1.Push(node1.right);s2.Push(node2.left);}returns1.Count==0&&s2.Count==0;}staticvoidMain(string[]args){// Creating a sample symmetric binary tree// 10// / \// 5 5// / \// 2 2Noderoot=newNode(10);root.left=newNode(5);root.right=newNode(5);root.left.left=newNode(2);root.right.right=newNode(2);Console.WriteLine(isSymmetric(root)?"true":"false");}}
JavaScript
// Node StructureclassNode{constructor(val){this.data=val;this.left=this.right=null;}}functionisSymmetric(root){if(root===null){returntrue;}lets1=[];lets2=[];// Initialize the stacks with the // left and right subtreess1.push(root.left);s2.push(root.right);while(s1.length>0&&s2.length>0){// Get the current pair of nodesletnode1=s1.pop();letnode2=s2.pop();// If both nodes are null, continue to the next pairif(node1===null&&node2===null){continue;}if(node1===null||node2===null||node1.data!==node2.data){returnfalse;}// Push children of node1 and node2 in opposite order// Push left child of node1 and right child of node2s1.push(node1.left);s2.push(node2.right);// Push right child of node1 and left child of node2s1.push(node1.right);s2.push(node2.left);}returns1.length===0&&s2.length===0;}// Driver Code// Creating a sample symmetric binary tree// 10// / \// 5 5// / \// 2 2letroot=newNode(10);root.left=newNode(5);root.right=newNode(5);root.left.left=newNode(2);root.right.right=newNode(2);console.log(isSymmetric(root));
Output
true
[Approach - 3] Using Queue - O(n) Time and O(n) Space
The 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.
C++
#include<iostream>#include<queue>usingnamespacestd;// Node StructureclassNode{public:intdata;Node*left,*right;Node(intval){data=val;left=right=nullptr;}};boolisSymmetric(Node*root){if(root==nullptr){returntrue;}queue<Node*>q;// Initialize the queue with the left // and right subtreesq.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 pairif(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 symmetricif(node1==nullptr||node2==nullptr||node1->data!=node2->data){returnfalse;}// Enqueue children in opposite // order to compare themq.push(node1->left);q.push(node2->right);q.push(node1->right);q.push(node2->left);}returntrue;}intmain(){// Creating a sample symmetric binary tree// 10// / \ // 5 5// / \ // 2 2Node*root=newNode(10);root->left=newNode(5);root->right=newNode(5);root->left->left=newNode(2);root->right->right=newNode(2);if(isSymmetric(root)){cout<<"true";}elsecout<<"false";return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;// Node StructureclassNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}classGfG{staticbooleanisSymmetric(Noderoot){if(root==null){returntrue;}Queue<Node>q=newLinkedList<>();// Initialize the queue with the left and right// subtreesq.offer(root.left);q.offer(root.right);while(!q.isEmpty()){Nodenode1=q.poll();Nodenode2=q.poll();// If both nodes are null, continue to the next// pairif(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 symmetricif(node1==null||node2==null||node1.data!=node2.data){returnfalse;}// Enqueue children in opposite order to compare// themq.offer(node1.left);q.offer(node2.right);q.offer(node1.right);q.offer(node2.left);}returntrue;}publicstaticvoidmain(String[]args){// Creating a sample symmetric binary tree// 10// / \// 5 5// / \// 2 2Noderoot=newNode(10);root.left=newNode(5);root.right=newNode(5);root.left.left=newNode(2);root.right.right=newNode(2);if(isSymmetric(root))System.out.println("true");elseSystem.out.println("false");}}
Python
fromcollectionsimportdeque# Node StructureclassNode:def__init__(self,val=0,left=None,right=None):self.data=valself.left=leftself.right=rightdefisSymmetric(root):ifrootisNone:returnTrueq=deque()# Initialize the queue with the left and right subtreesq.append(root.left)q.append(root.right)whileq:node1=q.popleft()node2=q.popleft()# If both nodes are None, continueifnode1isNoneandnode2isNone:continue# If only one is None or values don't match, it's not symmetricifnode1isNoneornode2isNoneornode1.data!=node2.data:returnFalse# Enqueue children in opposite orderq.append(node1.left)q.append(node2.right)q.append(node1.right)q.append(node2.left)returnTrueif__name__=="__main__":# Creating a sample symmetric binary tree# 10# / \# 5 5# / \# 2 2root=Node(10)root.left=Node(5)root.right=Node(5)root.left.left=Node(2)root.right.right=Node(2)print("true"ifisSymmetric(root)else"false")
C#
usingSystem;usingSystem.Collections.Generic;// Node StructureclassNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classGFG{staticboolisSymmetric(Noderoot){if(root==null){returntrue;}Queue<Node>q=newQueue<Node>();// Initialize the queue with the // left and right subtreesq.Enqueue(root.left);q.Enqueue(root.right);while(q.Count>0){Nodenode1=q.Dequeue();Nodenode2=q.Dequeue();// If both nodes are null, // continue to the next pairif(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 symmetricif(node1==null||node2==null||node1.data!=node2.data){returnfalse;}// Enqueue children in opposite // order to compare themq.Enqueue(node1.left);q.Enqueue(node2.right);q.Enqueue(node1.right);q.Enqueue(node2.left);}returntrue;}staticvoidMain(){// Creating a sample symmetric binary tree// 10// / \// 5 5// / \// 2 2Noderoot=newNode(10);root.left=newNode(5);root.right=newNode(5);root.left.left=newNode(2);root.right.right=newNode(2);Console.WriteLine(isSymmetric(root)?"true":"false");}}
JavaScript
// Node StructureclassNode{constructor(val){this.data=val;this.left=this.right=null;}}// Simple Queue classclassQueue{constructor(){this.items=[];this.head=0;}enqueue(val){this.items.push(val);}dequeue(){if(this.isEmpty())returnnull;constval=this.items[this.head];this.head++;// Optional: clean up memory if head is largeif(this.head>50){this.items=this.items.slice(this.head);this.head=0;}returnval;}isEmpty(){returnthis.head>=this.items.length;}}functionisSymmetric(root){if(root===null){returntrue;}constq=newQueue();// Initialize the queue with the left// and right subtreesq.enqueue(root.left);q.enqueue(root.right);while(!q.isEmpty()){constnode1=q.dequeue();constnode2=q.dequeue();// If both nodes are null, // continue to the next pairif(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 symmetricif(node1===null||node2===null||node1.data!==node2.data){returnfalse;}// Enqueue children in opposite // order to compare themq.enqueue(node1.left);q.enqueue(node2.right);q.enqueue(node1.right);q.enqueue(node2.left);}returntrue;}// Driver Code// Creating a sample symmetric binary tree// 10// / \// 5 5// / \// 2 2letroot=newNode(10);root.left=newNode(5);root.right=newNode(5);root.left.left=newNode(2);root.right.right=newNode(2);console.log(isSymmetric(root)?"true":"false");