Determine if Two Trees are Identical | Symmetric Tree(Mirror Image)

I came across these 2 questions and found a similarity in the logic part.

1. Symmetric Tree:

We need to check symmetry for the same tree or say mirror image.

`Input:         5       /   \      1     1     /       \    2         2Output: TrueExplanation: Tree is mirror image ofitself i.e. tree is symmetric`

Here comes the solution for the same.

`/*class of the node of the tree is asclass 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 notclass 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!

Happy Coding!

Software Developer

More from Vipul Gupta

Software Developer

The dual operating madness of SAFe

Get the Medium app