Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).Return 0 / 1 ( 0 for false, 1 for true ) for this problem.

“A symmetric tree is defined as a tree which is mirror image of itself about the root node.”

Example 1:
Input: 1 / \ 9 9 / \ / \ 5 4 4 5 Output: True or 1 (Symmetric)
Example 2:
Input: 1 / \ 2 2 \ \ 3 3 Output: False or 0 (Not Symmetric)
Solution

To satisfied the symmetric property, at each node left sub-tree should be a replica of the right sub-tree. Similar to the problem to verify trees are identical, we can start traversal from the root and take two different copies of the same tree to verify left and right. At each iteration check if the node has left or right node.

Code

Output

1

We encourage you to write a comment if you have a better solution or having any doubt on the above topic.

Leave a Reply

Your email address will not be published. Required fields are marked *