Print all Palindromic Levels Of a Binary Tree
Given a Binary Tree, the task is to print all palindromic levels of this tree.
Palindrome Level Any level of a Binary tree is said to be a palindromic level if on traversing it from left to right, the result is same as traversing that level from right to left.
Input: 1 / \ 12 13 / / \ 11 6 11 \ / 2 2 Output: 1 11 6 11 2 2 Explanation: First, third and fourth levels are palindrome. Input: 7 / \ 22 22 / \ \ 3 6 3 / \ \ / 1 5 8 1 / 23 Output: 7 22 22 3 6 3 23 Explanation: First, second, third and fifth levels are palindrome.
Approach: In order to check if each level is a Palindromic level, we need to first do the Level Order Traversal of the Binary tree to get the values at each level. Then for each level, check if it a palindrome or not.
Here a Queue data structure is used to store the levels of the Tree while doing the Level Order Traversal.
Below is the implementation of the above approach:
10 13 13 21 22 22 21 8
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.