Given a binary tree, check whether it is a mirror of itself without recursion.
Input : 1 / \ 2 2 / \ / \ 3 4 4 3 Output : Symmetric Input : 1 / \ 2 2 \ \ 3 3 Output : Not Symmetric
We have discussed recursive approach to solve this problem in below post :
In this post, iterative approach is discussed. We use Queue here. Note that for a symmetric that elements at every level are palindromic. In example 2, at the leaf level- the elements are which is not palindromic.
In other words,
1. The left child of left subtree = right child of right subtree.
2. The right child of left subtree = left child of right subtree.
If we insert the left child of left subtree first followed by right child of the right subtree in the queue, we only need to ensure that these are equal.
Similarly, If we insert the right child of left subtree followed by left child of the right subtree in the queue, we again need to ensure that these are equal.
Below is the implementation based on above idea.
The given tree is Symmetric
This article is contributed by Saloni Baweja. 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.
- Iterative approach to check if a Binary Tree is Perfect
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Iterative approach to check for children sum property in a Binary Tree
- Get level of a node in binary tree | iterative approach
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Deepest right leaf node in a binary tree | Iterative approach
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Construct Binary Tree from given Parent Array representation | Iterative Approach
- Deepest left leaf node in a binary tree | iterative approach
- Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
- Iterative Search for a key 'x' in Binary Tree
- Iterative diagonal traversal of binary tree
- Iterative Boundary traversal of Complete Binary tree
- Iterative method to find ancestors of a given binary tree