Posts Symmetric Tree (geeksforgeeks - SDE Sheet)
Post
Cancel

Symmetric Tree (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given a Binary Tree. Check whether it is Symmetric or not, i.e. whether the binary tree is a Mirror image of itself or not.

geeksforgeeks

SOLUTION

create helper method isSame(r1, r2)

compare r1 and r2 values.

Then recursively check isSame(r1.left, r2.right) && isSame(r1.right, r2.left)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class GfG
{

    public static boolean isSymmetric(Node root)
    {
        return isSame(root, root);
    }

    public static boolean isSame(Node r1, Node r2){

        // If both nodes are null, they are symmetric (mirror images of each other).
        if(r1 == null && r2 == null)
            return true;

        // If one of the nodes is null and the other is not, they are not symmetric.
        if(r1 == null || r2 == null)
            return false;

        // If the data in the current nodes doesn't match, they are not symmetric.
        if(r1.data != r2.data)
            return false;

        // Recursively check if the left subtree of r1 is the mirror of the right subtree of r2
        // and the right subtree of r1 is the mirror of the left subtree of r2.
        return isSame(r1.left, r2.right) && isSame(r1.right, r2.left);
    }
}
This post is licensed under CC BY 4.0 by the author.