Print all Palindromic Levels Of a Binary Tree

Given a Binary Tree, the task is to print all palindromic levels of this tree.

Palindrom 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.

Examples:

Input: 
                 1
                /  \ 
              12    13 
             /     /   \ 
            11    6     11 
                   \    / 
                   2   2  
Output:
1
11 6 11
2 2
Explanation:
First, third and fourth levels are plaindrome.

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 plaindrome.

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:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for printing a
// Palindromic Levels of Binary Tree
  
#include <bits/stdc++.h>
using namespace std;
  
// A Tree node
struct Node {
    int key;
    struct Node *left, *right;
};
  
// Utility function to create a new node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}
  
// Function to print a Palindromic level
void printLevel(struct Node* queue[],
                int index, int size)
{
    for (int i = index; i < size; i++) {
        cout << queue[i]->key << " ";
    }
  
    cout << endl;
}
  
// Function to check whether given level
// is Palindromic level or not
bool isPalindrome(struct Node* queue[],
                  int index, int size)
{
  
    while (index < size) {
        // check value of two nodes are
        // equal or not
        if (queue[index++]->key
            != queue[size--]->key)
            return false;
    }
  
    return true;
}
  
// Utility function to get palindromic
// level of a given Binary tree
void printPalLevel(struct Node* node,
                   struct Node* queue[],
                   int index, int size)
{
  
    // Print root node value
    // as a single value in a
    // level is also a Palindrome
    cout << queue[index]->key << endl;
  
    // Level order traversal of Tree
    while (index < size) {
        int curr_size = size;
        while (index < curr_size) {
            struct Node* temp = queue[index];
  
            if (temp->left != NULL) {
                queue[size++] = temp->left;
            }
  
            if (temp->right != NULL) {
                queue[size++] = temp->right;
            }
  
            index++;
        }
  
        // Check if level is Palindrome or not
        if (isPalindrome(queue, index, size - 1)) {
            printLevel(queue, index, size);
        }
    }
}
  
// Function to find total no of nodes
int findSize(struct Node* node)
{
  
    if (node == NULL)
        return 0;
  
    return 1
           + findSize(node->left)
           + findSize(node->right);
}
  
// Function to find palindromic level
// In a given binary tree
void printPalindromicLevel(struct Node* node)
{
    int t_size = findSize(node);
    struct Node* queue[t_size];
    queue[0] = node;
    printPalLevel(node, queue, 0, 1);
}
  
// Driver Code
int main()
{
    /*     10 
        /    \ 
       13     13 
        /       \ 
        14        15 
        / \        / \ 
       21 22      22 21
                     /
                    8 */
  
    // Create Binary Tree as shown
    Node* root = newNode(10);
    root->left = newNode(13);
    root->right = newNode(13);
  
    root->right->left = newNode(14);
    root->right->right = newNode(15);
  
    root->right->left->left = newNode(21);
    root->right->left->right = newNode(22);
    root->right->right->left = newNode(22);
    root->right->right->right = newNode(21);
    root->right->right->right->left = newNode(8);
  
    // Print Palindromic Levels
    printPalindromicLevel(root);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for printing a
// Palindromic Levels of Binary Tree
class GFG{
   
// A Tree node
static class Node {
    int key;
    Node left, right;
};
   
// Utility function to create a new node
static Node newNode(int key)
{
    Node temp = new Node();
    temp.key = key;
    temp.left = temp.right = null;
    return (temp);
}
   
// Function to print a Palindromic level
static void printLevel(Node queue[],
                int index, int size)
{
    for (int i = index; i < size; i++) {
        System.out.print(queue[i].key+ " ");
    }
   
    System.out.println();
}
   
// Function to check whether given level
// is Palindromic level or not
static boolean isPalindrome(Node queue[],
                  int index, int size)
{
   
    while (index < size) {
        // check value of two nodes are
        // equal or not
        if (queue[index++].key
            != queue[size--].key)
            return false;
    }
   
    return true;
}
   
// Utility function to get palindromic
// level of a given Binary tree
static void printPalLevel(Node node,
                   Node queue[],
                   int index, int size)
{
   
    // Print root node value
    // as a single value in a
    // level is also a Palindrome
    System.out.print(queue[index].key +"\n");
   
    // Level order traversal of Tree
    while (index < size) {
        int curr_size = size;
        while (index < curr_size) {
            Node temp = queue[index];
   
            if (temp.left != null) {
                queue[size++] = temp.left;
            }
   
            if (temp.right != null) {
                queue[size++] = temp.right;
            }
   
            index++;
        }
   
        // Check if level is Palindrome or not
        if (isPalindrome(queue, index, size - 1)) {
            printLevel(queue, index, size);
        }
    }
}
   
// Function to find total no of nodes
static int findSize(Node node)
{
   
    if (node == null)
        return 0;
   
    return 1
           + findSize(node.left)
           + findSize(node.right);
}
   
// Function to find palindromic level
// In a given binary tree
static void printPalindromicLevel(Node node)
{
    int t_size = findSize(node);
    Node []queue = new Node[t_size];
    queue[0] = node;
    printPalLevel(node, queue, 0, 1);
}
   
// Driver Code
public static void main(String[] args)
{
    /*     10 
        /    \ 
       13     13 
        /       \ 
        14        15 
        / \        / \ 
       21 22      22 21
                     /
                    8 */
   
    // Create Binary Tree as shown
    Node root = newNode(10);
    root.left = newNode(13);
    root.right = newNode(13);
   
    root.right.left = newNode(14);
    root.right.right = newNode(15);
   
    root.right.left.left = newNode(21);
    root.right.left.right = newNode(22);
    root.right.right.left = newNode(22);
    root.right.right.right = newNode(21);
    root.right.right.right.left = newNode(8);
   
    // Print Palindromic Levels
    printPalindromicLevel(root);
   
}
}
  
// This code is contributed by Rajput-Ji

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for printing a
// Palindromic Levels of Binary Tree
using System;
  
class GFG{
    
// A Tree node
class Node {
    public int key;
    public Node left, right;
};
    
// Utility function to create a new node
static Node newNode(int key)
{
    Node temp = new Node();
    temp.key = key;
    temp.left = temp.right = null;
    return (temp);
}
    
// Function to print a Palindromic level
static void printLevel(Node []queue,
                int index, int size)
{
    for (int i = index; i < size; i++) {
        Console.Write(queue[i].key+ " ");
    }
    
    Console.WriteLine();
}
    
// Function to check whether given level
// is Palindromic level or not
static bool isPalindrome(Node []queue,
                  int index, int size)
{
    
    while (index < size) {
        // check value of two nodes are
        // equal or not
        if (queue[index++].key
            != queue[size--].key)
            return false;
    }
    
    return true;
}
    
// Utility function to get palindromic
// level of a given Binary tree
static void printPalLevel(Node node,
                   Node []queue,
                   int index, int size)
{
    
    // Print root node value
    // as a single value in a
    // level is also a Palindrome
    Console.Write(queue[index].key +"\n");
    
    // Level order traversal of Tree
    while (index < size) {
        int curr_size = size;
        while (index < curr_size) {
            Node temp = queue[index];
    
            if (temp.left != null) {
                queue[size++] = temp.left;
            }
    
            if (temp.right != null) {
                queue[size++] = temp.right;
            }
    
            index++;
        }
    
        // Check if level is Palindrome or not
        if (isPalindrome(queue, index, size - 1)) {
            printLevel(queue, index, size);
        }
    }
}
    
// Function to find total no of nodes
static int findSize(Node node)
{
    
    if (node == null)
        return 0;
    
    return 1
           + findSize(node.left)
           + findSize(node.right);
}
    
// Function to find palindromic level
// In a given binary tree
static void printPalindromicLevel(Node node)
{
    int t_size = findSize(node);
    Node []queue = new Node[t_size];
    queue[0] = node;
    printPalLevel(node, queue, 0, 1);
}
    
// Driver Code
public static void Main(String[] args)
{
    /*     10 
        /    \ 
       13     13 
        /       \ 
        14        15 
        / \        / \ 
       21 22      22 21
                     /
                    8 */
    
    // Create Binary Tree as shown
    Node root = newNode(10);
    root.left = newNode(13);
    root.right = newNode(13);
    
    root.right.left = newNode(14);
    root.right.right = newNode(15);
    
    root.right.left.left = newNode(21);
    root.right.left.right = newNode(22);
    root.right.right.left = newNode(22);
    root.right.right.right = newNode(21);
    root.right.right.right.left = newNode(8);
    
    // Print Palindromic Levels
    printPalindromicLevel(root);
    
}
}
   
// This code is contributed by sapnasingh4991

chevron_right


Output:

10
13 13 
21 22 22 21 
8

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Rajput-Ji, sapnasingh4991