Determine if Two Trees are Identical | Symmetric Tree(Mirror Image)
2 min readApr 28, 2021
I came across these 2 questions and found a similarity in the logic part.
- Symmetric Tree:
We need to check symmetry for the same tree or say mirror image.
Input:
5
/ \
1 1
/ \
2 2
Output: True
Explanation: Tree is mirror image of
itself i.e. tree is symmetric
Here comes the solution for the same.
/*
class of the node of the tree is as
class Node{
int data;
Node left;
Node right;
Node(int data){
this.data = data;
left=null;
right=null;
}
}*/
// complete this function
// return true/false if the is Symmetric or not
class GfG
{
// return true/false denoting whether the tree is Symmetric or not
public static boolean isSymmetric(Node root){
if(root==null)
return true;
return isTreeSame(root.left,root.right);
}
public static boolean isTreeSame(Node left,Node right){
if(left==null || right == null){
return left == right;
}
if(left.data!=right.data)
return false;
return isTreeSame(left.left,right.right)&&isTreeSame(left.right,right.left);
}
}
2. Determine 2 Trees are identical or not.
Here we need to check the symmetry for 2 trees.
/*class Node{
int data;
Node left,right;
Node(int d){
data=d;
left=right=null;
}
}*/class Solution
{
//Function to check if two trees are identical.
boolean isIdentical(Node root1, Node root2)
{
return isSymmetric(root1,root2);
}
boolean isSymmetric(Node left,Node right){
if(left==null || right==null)
return left==right;
if(left.data!=right.data)
return false;
return isSymmetric(left.left,right.left) &&isSymmetric(left.right,right.right);
}
}
Here if you can see both the solutions the difference is just 1 line of code:
for Symmetric:
isTreeSame(left.left,right.right)&&isTreeSame(left.right,right.left);
for Two trees identical
return isSymmetric(left.left,right.left) &&isSymmetric(left.right,right.right);
The rest of the code is the same!
Thank you for reading!
Happy Coding!