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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Iterative approach to check if a Binary Tree is Perfect
- Iterative approach to check for children sum property in a Binary Tree
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Get level of a node in 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
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
- Deepest left leaf node in a binary tree | iterative approach
- Iterative Approach to check if two Binary Trees are Isomorphic or not
- Symmetric Binary Tree
- Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
- Print all nodes at distance K from given node: Iterative Approach
- Smallest number in BST which is greater than or equal to N ( Iterative Approach)
- Symmetric Tree (Mirror Image of itself)
- Check if a Binary Tree is BST : Simple and Efficient Approach
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Iterative Method to find Height of Binary Tree