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.
Below is the implementation of above approach:
Time complexity: O(N)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Print nodes at k distance from root
- Lowest Common Ancestor in a Binary Tree | Set 1
- Delete leaf nodes with value k
- Smallest number in BST which is greater than or equal to N
- Find the maximum node at a given level in a binary tree
- Maximize the total profit of all the persons
- Reverse nodes of a linked list without affecting the special characters
- Pair with minimum absolute difference after solving each query
- Sum of cousins of a given node in a Binary Tree
- Applications of Graph Data Structure