Print all Palindromic Levels of a Binary Tree


In this problem, we will print each palindromic level of the given binary tree. We can use the breadth−first search algorithm to traverse each level of the given binary tree and check whether a particular level of the binary tree is palindromic. If yes, we print the level in the output.

Problem statement − We have given a binary tree, and we need to print all palindromic levels of the binary tree. If any particular level of the binary tree contains the same numbers from left to right and right to left, we can say that the current level is palindromic.

Sample examples

Input 

                  9      
                /    \ 
              23      83 
            /        /   \ 
           90      76     90 
                   \    / 
                   7   7  

Output 

9
90  76  90
7  7

Explanation − The first, third, and fourth levels are palindromic.

Input 

                  19
                /    \ 
              23    23 
            /        /   \ 
          80      80     80 
                   \    / 
                   4   4  

Output 

19
23  23
80  80  80
4  4

Explanation − All levels of the binary tree are palindromic.

Approach 1

We will use the queue data structure to perform the level order traversal on the binary tree in this approach. The level order traversal traverses through each level of the binary tree. While traversing each level, we can check whether the current level is palindromic or not.

Algorithm

Step 1 −Create a structure of the node of the binary tree.

Step 2 −Define the createNewNode() function to create a new node of the binary tree. The createNewNode() function creates a new node and initializes the left and right pointer with NULL.

Step 3 − Create a binary tree in the main() method.

Step 4 −Execute the getSize() function to get the height of the binary tree.

Step 4.1 −In the getSize() function, if the head node is NULL, return 0.

Step 4.2 −Otherwise, make a recursive call for the left child and right child of the current node, and add 1 to its returned value.

Step 5 −Create a queue of size equal to the height of the binary tree, and insert the head node into the queue.

Step 6 −Execute the printPalindromicLevel() function to traverse through each level and find the palindromic levels.

Step 6.1 −Print the first node, as it will always be palindromic.

Step 6.2 − Use the while loop to make iterations until ‘ind’ is less than ‘size’ to traverse each level.

Step 6.3 −Use another while loop to traverse the current level.

Step 6.4 −In the nested while loop, take a current node from the queue.

Step 6.5 −If the left and right node of the current node exists, insert them into the queue.

Step 6.6 −Increment the ‘ind’ by 1.

Step 6.7 −Execute the isLevelPalindrome() function to check whether the current level is palindromic.

Step 6.7.1 −Traverse the queue, and compare elements from start to end.

Step 6.7.2 −If any element doesn’t match from start and end, return false.

Step 6.7.3 −Return true at the end.

Step 6.8 −If isLevelPalindrome(), execute the showLevel() function to print the current level. In the function, we traverse the queue and print each element of the queue.

Example

#include <bits/stdc++.h>
using namespace std;
// Tree structure
struct TreeNode {
    int val;
    struct TreeNode *left, *right;
};
// Function for creating new node
TreeNode *createNewNode(int val) {
    TreeNode *tmp = new TreeNode;
    tmp->val = val;
    tmp->left = NULL;
    tmp->right = NULL;
    return (tmp);
}
bool isLevelPalindrome(struct TreeNode *que[], int ind, int sz) {
    while (ind < sz) {
        // Check for the palindrome string
        if (que[ind++]->val != que[sz--]->val)
            return false;
    }
    return true;
}
// Print the particular level of a given
void showLevel(struct TreeNode *que[], int ind, int sz) {
    // Traverse the queue and print all values
    for (int p = ind; p < sz; p++) {
        cout << que[p]->val << " ";
    }
    cout << endl;
}
void printPalindromicLevel(struct TreeNode *head, struct TreeNode *que[], int ind, int size) {
    // Root node is always palindrome
    cout << que[ind]->val << endl;
    while (ind < size) {
        int temp_size = size;
        while (ind < temp_size) { 
            struct TreeNode *temp = que[ind];
            if (temp->left != NULL) {
                que[size++] = temp->left;
            }
            if (temp->right != NULL) {
                que[size++] = temp->right;
            }
            ind++;
        }
        if (isLevelPalindrome(que, ind, size - 1)) {
            showLevel(que, ind, size);
        }
    }
}
// Get the size of the tree
int getSize(struct TreeNode *head) {
    // Base condition
    if (head == NULL)
        return 0;
    return 1 + getSize(head->left) + getSize(head->right);
}
void showPalindromeLevel(struct TreeNode *head) {
    int temp_size = getSize(head);
    struct TreeNode *que[temp_size];
    que[0] = head;
    printPalindromicLevel(head, que, 0, 1);
}
int main() {
    TreeNode *head = createNewNode(5);
    head->left = createNewNode(11);
    head->right = createNewNode(11);
    head->left->left = createNewNode(3);
    head->left->right = createNewNode(5);
    head->right->right = createNewNode(3);
    head->left->left->left = createNewNode(54);
    head->left->left->right = createNewNode(17);
    cout << "The palindromic levels are - "<< endl;
    showPalindromeLevel(head);
    return 0;
}

Output

The palindromic levels are − 
5
11 11 
3 5 3 

Time complexity − O(N) as we traverse each node.

Space complexity − O(N) as we store nodes of binary tree in Queue.

We learned to travese to each level of the binary tree and check if any level is palindromic. Also, programmers can try to write the code to print in which they need to print the even levels. In which we need to print the levels containing only even numbers.

Updated on: 22-Jul-2023

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements