Open In App

Check if the level order traversal of a Binary Tree results in a palindrome

Last Updated : 26 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary tree and the task if to check if it’s level order traversal results in a palindrome or not.
Examples: 
 

Input: 
 

Output: Yes 
RADAR is the level order traversal of the 
given tree which is a palindrome.
Input: 
 

Output: No 
 

 

Approach: 
 

  • Traverse the Binary Tree in level order and store the nodes in a stack.
  • Traverse the Binary Tree in level order once again and compare the data in the node with the data at top of stack.
  • In case there is a match, move on to the next node.
  • In case there is a mismatch, stop and print No.

Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure for a node of the tree
struct node {
    char data;
    node *left, *right;
};
 
// Function to add a node
// to the Binary Tree
node* add(char data)
{
    node* newnode = new node;
    newnode->data = data;
    newnode->left = newnode->right = NULL;
    return newnode;
}
 
// Function to perform level order traversal
// of the Binary Tree and add the nodes to
// the stack
void findInv(node* root, stack<node*>& S)
{
    if (root == NULL)
        return;
 
    // The queue holds the nodes which are being
    // processed starting from the root
    queue<node*> Q;
    Q.push(root);
    while (Q.size()) {
        node* temp = Q.front();
        Q.pop();
 
        // Take the node out of the Queue
        // and push it to the stack
        S.push(temp);
 
        // If there is a left child
        // then push it to the queue
        if (temp->left != NULL)
            Q.push(temp->left);
 
        // If there is a right child
        // then push it to the queue
        if (temp->right != NULL)
            Q.push(temp->right);
    }
}
 
// Function that returns true if the
// level order traversal of the
// tree results in a palindrome
bool isPalindrome(stack<node*> S, node* root)
{
    queue<node*> Q;
    Q.push(root);
    while (Q.size()) {
 
        // To store the element at
        // the front of the queue
        node* temp = Q.front();
 
        // To store the element at
        // the top of the stack
        node* temp1 = S.top();
        S.pop();
        Q.pop();
 
        // If the data in the node at the top
        // of stack does not match the data
        // in the node at the front of the queue
        if (temp->data != temp1->data)
            return false;
        if (temp->left != NULL)
            Q.push(temp->left);
        if (temp->right != NULL)
            Q.push(temp->right);
    }
 
    // If there is no mismatch
    return true;
}
 
// Driver code
int main()
{
 
    // Creating the binary tree
    node* root = add('R');
    root->left = add('A');
    root->right = add('D');
    root->left->left = add('A');
    root->left->right = add('R');
 
    // Stack to store the nodes of the
    // tree in level order traversal
    stack<node*> S;
    findInv(root, S);
 
    // If the level order traversal
    // results in a palindrome
    if (isPalindrome(S, root))
        cout << "Yes";
    else
        cout << "NO";
 
    return 0;
}


Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Structure for a node of the tree
static class node
{
    char data;
    node left, right;
};
 
// Function to add a node
// to the Binary Tree
static node add(char data)
{
    node newnode = new node();
    newnode.data = data;
    newnode.left = newnode.right = null;
    return newnode;
}
 
// Function to perform level order traversal
// of the Binary Tree and add the nodes to
// the stack
static void findInv(node root, Stack<node> S)
{
    if (root == null)
        return;
 
    // The queue holds the nodes which are being
    // processed starting from the root
    Queue<node> Q = new LinkedList<>();
    Q.add(root);
    while (Q.size() > 0)
    {
        node temp = Q.peek();
        Q.remove();
 
        // Take the node out of the Queue
        // and push it to the stack
        S.add(temp);
 
        // If there is a left child
        // then push it to the queue
        if (temp.left != null)
            Q.add(temp.left);
 
        // If there is a right child
        // then push it to the queue
        if (temp.right != null)
            Q.add(temp.right);
    }
}
 
// Function that returns true if the
// level order traversal of the
// tree results in a palindrome
static boolean isPalindrome(Stack<node> S, node root)
{
    Queue<node> Q = new LinkedList<>();
    Q.add(root);
    while (Q.size() > 0)
    {
 
        // To store the element at
        // the front of the queue
        node temp = Q.peek();
 
        // To store the element at
        // the top of the stack
        node temp1 = S.peek();
        S.pop();
        Q.remove();
 
        // If the data in the node at the top
        // of stack does not match the data
        // in the node at the front of the queue
        if (temp.data != temp1.data)
            return false;
        if (temp.left != null)
            Q.add(temp.left);
        if (temp.right != null)
            Q.add(temp.right);
    }
 
    // If there is no mismatch
    return true;
}
 
// Driver code
public static void main(String[] args)
{
 
    // Creating the binary tree
    node root = add('R');
    root.left = add('A');
    root.right = add('D');
    root.left.left = add('A');
    root.left.right = add('R');
 
    // Stack to store the nodes of the
    // tree in level order traversal
    Stack<node> S = new Stack<node>();
    findInv(root, S);
 
    // If the level order traversal
    // results in a palindrome
    if (isPalindrome(S, root))
        System.out.print("Yes");
    else
        System.out.print("NO");
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python implementation of the approach
 
# Linked List node
class Node:
    def __init__(self, data):
        self.info = data
        self.left = None
        self.right = None
 
# Function to append a node
# to the Binary Tree
def append(data):
 
    newnode = Node(0)
    newnode.data = data
    newnode.left = newnode.right = None
    return newnode
 
# Function to perform level order traversal
# of the Binary Tree and append the nodes to
# the stack
def findInv(root, S):
 
    if (root == None):
        return
 
    # The queue holds the nodes which are being
    # processed starting from the root
    Q = []
    Q.append(root)
    while (len(Q) > 0) :
     
        temp = Q[0]
        Q.pop(0)
 
        # Take the node out of the Queue
        # and push it to the stack
        S.append(temp)
 
        # If there is a left child
        # then push it to the queue
        if (temp.left != None):
            Q.append(temp.left)
 
        # If there is a right child
        # then push it to the queue
        if (temp.right != None):
            Q.append(temp.right)
     
# Function that returns True if the
# level order traversal of the
# tree results in a palindrome
def isPalindrome(S,root):
 
    Q = []
    Q.append(root)
    while (len(Q) > 0) :
     
        # To store the element at
        # the front of the queue
        temp = Q[0]
 
        # To store the element at
        # the top of the stack
        temp1 = S[-1]
        S.pop()
        Q.pop(0)
 
        # If the data in the node at the top
        # of stack does not match the data
        # in the node at the front of the queue
        if (temp.data != temp1.data):
            return False
        if (temp.left != None):
            Q.append(temp.left)
        if (temp.right != None):
            Q.append(temp.right)
 
    # If there is no mismatch
    return True
 
# Driver code
 
# Creating the binary tree
root = append('R')
root.left = append('A')
root.right = append('D')
root.left.left = append('A')
root.left.right = append('R')
 
# Stack to store the nodes of the
# tree in level order traversal
S = []
findInv(root, S)
 
# If the level order traversal
# results in a palindrome
if (isPalindrome(S, root)):
    print("Yes")
else:
    print("NO")
 
# This code is contributed by Arnab Kundu


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Structure for a node of the tree
class node
{
    public char data;
    public node left, right;
};
 
// Function to.Add a node
// to the Binary Tree
static node add(char data)
{
    node newnode = new node();
    newnode.data = data;
    newnode.left = newnode.right = null;
    return newnode;
}
 
// Function to perform level order traversal
// of the Binary Tree and.Add the nodes to
// the stack
static void findInv(node root, Stack<node> S)
{
    if (root == null)
        return;
 
    // The queue holds the nodes which are being
    // processed starting from the root
    Queue<node> Q = new Queue<node>();
    Q.Enqueue(root);
    while (Q.Count > 0)
    {
        node temp = Q.Peek();
        Q.Dequeue();
 
        // Take the node out of the Queue
        // and push it to the stack
        S.Push(temp);
 
        // If there is a left child
        // then push it to the queue
        if (temp.left != null)
            Q.Enqueue(temp.left);
 
        // If there is a right child
        // then push it to the queue
        if (temp.right != null)
            Q.Enqueue(temp.right);
    }
}
 
// Function that returns true if the
// level order traversal of the
// tree results in a palindrome
static bool isPalindrome(Stack<node> S,
                               node root)
{
    Queue<node> Q = new Queue<node>();
    Q.Enqueue(root);
    while (Q.Count > 0)
    {
 
        // To store the element at
        // the front of the queue
        node temp = Q.Peek();
 
        // To store the element at
        // the top of the stack
        node temp1 = S.Peek();
        S.Pop();
        Q.Dequeue();
 
        // If the data in the node at the top
        // of stack does not match the data
        // in the node at the front of the queue
        if (temp.data != temp1.data)
            return false;
        if (temp.left != null)
            Q.Enqueue(temp.left);
        if (temp.right != null)
            Q.Enqueue(temp.right);
    }
 
    // If there is no mismatch
    return true;
}
 
// Driver code
public static void Main(String[] args)
{
 
    // Creating the binary tree
    node root = add('R');
    root.left = add('A');
    root.right = add('D');
    root.left.left = add('A');
    root.left.right = add('R');
 
    // Stack to store the nodes of the
    // tree in level order traversal
    Stack<node> S = new Stack<node>();
    findInv(root, S);
 
    // If the level order traversal
    // results in a palindrome
    if (isPalindrome(S, root))
        Console.Write("Yes");
    else
        Console.Write("NO");
}
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
// JavaScript implementation of the approach
 
// Structure for a node of the tree
class node
{
    constructor()
    {
        this.data = '';
        this.left = null;
        this.right = null;
    }
};
 
// Function to.Add a node
// to the Binary Tree
function add(data)
{
    var newnode = new node();
    newnode.data = data;
    newnode.left = newnode.right = null;
    return newnode;
}
 
// Function to perform level order traversal
// of the Binary Tree and.Add the nodes to
// the stack
function findInv(root, S)
{
    if (root == null)
        return;
 
    // The queue holds the nodes which are being
    // processed starting from the root
    var Q = [];
    Q.push(root);
    while (Q.length > 0)
    {
        var temp = Q[0];
        Q.shift();
 
        // Take the node out of the Queue
        // and push it to the stack
        S.push(temp);
 
        // If there is a left child
        // then push it to the queue
        if (temp.left != null)
            Q.push(temp.left);
 
        // If there is a right child
        // then push it to the queue
        if (temp.right != null)
            Q.push(temp.right);
    }
}
 
// Function that returns true if the
// level order traversal of the
// tree results in a palindrome
function isPalindrome(S, root)
{
    var Q = [];
    Q.push(root);
    while (Q.length > 0)
    {
 
        // To store the element at
        // the front of the queue
        var temp = Q[0];
 
        // To store the element at
        // the top of the stack
        var temp1 = S[S.length-1];
        S.pop();
        Q.shift();
 
        // If the data in the node at the top
        // of stack does not match the data
        // in the node at the front of the queue
        if (temp.data != temp1.data)
            return false;
        if (temp.left != null)
            Q.push(temp.left);
        if (temp.right != null)
            Q.push(temp.right);
    }
 
    // If there is no mismatch
    return true;
}
 
// Driver code
// Creating the binary tree
var root = add('R');
root.left = add('A');
root.right = add('D');
root.left.left = add('A');
root.left.right = add('R');
// Stack to store the nodes of the
// tree in level order traversal
var S = [];
findInv(root, S);
// If the level order traversal
// results in a palindrome
if (isPalindrome(S, root))
    document.write("Yes");
else
    document.write("NO");
 
 
</script>


Output: 

Yes

 

Time Complexity: O(N).
Auxiliary Space: O(N). 



Similar Reads

Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration. Examples: Input: [caption width="800"] [/caption] Output: Pre Order: 1 2 4 5 3 6 7 Post Order: 4 5 2 6 7 3 1 In Order: 4 2 5 1 6 3 7 Input: [caption width="800"] [/caption] Output: Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11
9 min read
Level order traversal of Binary Tree using Morris Traversal
Given a binary tree, the task is to traverse the Binary Tree in level order fashion.Examples: Input: 1 / \ 2 3 Output: 1 2 3 Input: 5 / \ 2 3 \ 6 Output: 5 2 3 6 Approach: The idea is to use Morris Preorder Traversal to traverse the tree in level order traversal.Observations: There are mainly two observations for the traversal of the tree using Mor
11 min read
Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
Given the level order traversal of a Complete Binary Tree, determine whether the Binary Tree is a valid Min-Heap Examples: Input : level = [10, 15, 14, 25, 30] Output : True The tree of the given level order traversal is 10 / \ 15 14 / \ 25 30 We see that each parent has a value less than its child, and hence satisfies the min-heap property Input :
6 min read
Flatten Binary Tree in order of Level Order Traversal
Given a Binary Tree, the task is to flatten it in order of Level order traversal of the tree. In the flattened binary tree, the left node of all the nodes must be NULL.Examples: Input: 1 / \ 5 2 / \ / \ 6 4 9 3 Output: 1 5 2 6 4 9 3 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 1 2 3 4 5 Approach: We will solve this problem by simulating the Level order travers
7 min read
Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
Given a binary tree, print it vertically. The following example illustrates vertical order traversal. 1 / \ 2 3 / \ / \ 4 5 6 7 \ \ 8 9 The output of print this tree vertically will be: 4 2 1 5 6 3 8 7 9 We have discussed an efficient approach in below post.Print a Binary Tree in Vertical Order | Set 2 (Hashmap based Method)The above solution uses
10 min read
Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
Given a Binary Search Tree, the task is to print the nodes of the BST in the following order: If the BST contains levels numbered from 1 to N then, the printing order is level 1, level N, level 2, level N - 1, and so on.The top-level order (1, 2, …) nodes are printed from left to right, while the bottom level order (N, N-1, ...) nodes are printed f
18 min read
Check if the given array can represent Level Order Traversal of Binary Search Tree
Given an array of size n. The problem is to check whether the given array can represent the level order traversal of a Binary Search Tree or not. Examples: Input : arr[] = {7, 4, 12, 3, 6, 8, 1, 5, 10} Output : Yes For the given arr[] the Binary Search Tree is: 7 / \ 4 12 / \ / 3 6 8 / / \ 1 5 10 Input : arr[] = {11, 6, 13, 5, 12, 10} Output : No T
12 min read
Insertion in n-ary tree in given order and Level order traversal
Given a set of parent nodes where the index of the array is the child of each Node value, the task is to insert the nodes as a forest(multiple trees combined together) where each parent could have more than two children. After inserting the nodes, print each level in a sorted format. Example: Input: arr[] = {5, 3, -1, 2, 5, 3} Output:-1 231 5Input:
10 min read
Connect Nodes at same Level (Level Order Traversal)
Write a function to connect all the adjacent nodes at the same level in a binary tree. Example: Input Tree A / \ B C / \ \ D E F Output Tree A---&gt;NULL / \ B--&gt;C--&gt;NULL / \ \ D--&gt;E--&gt;F--&gt;NULL We have already discussed O(n^2) time and O approach in Connect nodes at same level as morris traversal in worst case can be O(n) and calling
9 min read
Perfect Binary Tree Specific Level Order Traversal
Given a Perfect Binary Tree like below: Print the level order of nodes in following specific manner: 1 2 3 4 7 5 6 8 15 9 14 10 13 11 12 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24i.e. print nodes in level order but nodes should be from left and right side alternatively. Here 1st and 2nd levels are trivial. While 3rd level: 4(left), 7(right), 5
20 min read
Practice Tags :