Problem Statement:
You are given a binary tree, where the data present in each node is an integer. You have to find whether the given tree is symmetric or not.
Symmetric tree is a binary tree, whose mirror image is exactly the same as the original tree.
Input Format:
the binary tree node elements in the level order form
Output Format:
The output consists of a single line containing “Symmetric” if the given tree is symmetric, else “Asymmetric”.
Sample Input 1:
1 2 2 3 4 4 3 -1 -1 -1 -1 -1 -1 -1 -1
Sample Output 1:
Symmetric
Sample Input 2:
1 2 3 4 -1 -1 -1 -1 -1
Sample Output 2:
Asymmetric
Constraint:
0 <= N <= 10⁵1 <= Data <= 10⁵
Approach:
A symmetrical binary tree is a tree that forms a mirror of itself around the center. In other words, every node in the left subtree will have a mirror image in the right subtree.
We can ignore the root node as it is lying on the mirror line. In the next level, for a symmetric tree, the node at the root’s left should be equal to the node at the root’s right.
If we take two variables root1 and root2 to represent the left child of root and right child of the root, then root 1 value=root 2 value.
Further, we need to understand that when root1’s value is equal to root2’s value, we need to further check for its children. As we are concerned about node positions through a mirror, root1’s left child should be checked with root2’s right child and root1’s right child should be checked with root2’s left child.
Code:
Thanks for Reading
Placewit grows the best engineers by providing an interactive classroom experience and by helping them develop their skills and get placed in amazing companies.
Learn more at Placewit. Follow us on Instagram and Facebook for daily learning.