![]() |
VOOZH | about |
Given two binary trees, the task is to check whether the two binary trees is a mirror of each other or not.
Mirror of a Binary Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged.
Trees in the above figure are mirrors of each other.
A recursive solution and an iterative method using inorder traversal to check whether the two binary trees is a mirror of each other or not have been already discussed. In this post a solution using level order traversal has been discussed.
The idea is to use a queue in which two nodes of both the trees which needs to be checked for equality are present together. At each step of level order traversal, get two nodes from the queue, check for their equality and then insert next two children nodes of these nodes which need to be checked for equality. During insertion step, first left child of first tree node and right child of second tree node are inserted. After this right child of first tree node and left child of second tree node are inserted. If at any stage one node is NULL and other is not, then both trees are not a mirror of each other.
Steps to solve this problem:
1. Check if a is null and b is null than return yes.
2. Check if a is null or b is null than return no.
3. Declare a queue q of pointer to a node and push a and b in it.
4. While q is not empty:
*Update a=q.front and pop the element.
*Update b=q.front and pop the element.
*Check if a->data is not equal to b->data than return no.
*Check if a->left is not null and b->right is not null than push a->left and b->right in the q.
*Else check if a->right is null or b ->left is not null than return no.
5. Return yes.
Below is the implementation of above approach:
Yes
Complexity Analysis: