Open In App

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

Last Updated : 21 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary tree. The task is to check if its level order traversal results in a palindrome or not.

Examples: 

Input: 

check_if_the_level_order_traversal_of_a_binary_tree-2_results_in_a_palindrome_2


Output: True
Explanation: RADAR is the level order traversal of the given tree which is a palindrome.

Input:

check_if_the_level_order_traversal_of_a_binary_tree_results_in_a_palindrome

Output: False
Explanation: RADARS is the level order traversal of the given tree which is not a palindrome.

Approach:

The idea is to traverse the binary tree using level order traversal and push the node values into a stack. Then traverse the binary tree again (level order). If the value of current node is equal to stack top, then pop the top element. Otherwise return false. After traversing the binary tree, return true.

Below is the implementation of the above approach: 

C++
// C++ program to check if level order
// traversal of binary tree is palindrome.
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    char data;
    Node* left, *right;
    Node (char x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Function that returns true if the
// level order traversal of the
// tree results in a palindrome
bool isPalindrome(Node* root) {
    if (root == nullptr) return true;
    
    queue<Node*> q;
    stack<int> st;
    q.push(root);
    
    // Traverse the tree and push the node 
    // values into stack.
    while (q.empty() == false) {
        Node* curr = q.front();
        q.pop();
        
        // Push the curr value into stack.
        st.push(curr->data);
        
        // Push left node
        if (curr->left != nullptr)
            q.push(curr->left);
        
        // Push right node
        if (curr->right != nullptr)
            q.push(curr->right);
    }
    
    // Again traverse the tree and compare
    // node values with stack top.
    q.push(root);
    while (q.empty() == false) {
        Node* curr = q.front();
        q.pop();
        
        // If values dont match, then 
        // it is not palindrome.
        if (curr->data != st.top())
            return false;
        else st.pop();
        
        if (curr->left != nullptr)
            q.push(curr->left);
        
        if (curr->right != nullptr)
            q.push(curr->right);
    }
    
    return true;
}

int main() {
    
    // Binary tree
    //       R
    //      / \
    //     A   D
    //   / \
    //   A   R
    Node* root = new Node('R');
    root->left = new Node('A');
    root->right = new Node('D');
    root->left->left = new Node('A');
    root->left->right = new Node('R');

    if (isPalindrome(root))
        cout << "True";
    else
        cout << "False";

    return 0;
}
Java
// Java program to check if level order
// traversal of binary tree is palindrome.
import java.util.*;

class Node {
    char data;
    Node left, right;

    Node(char x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Function that returns true if the
    // level order traversal of the
    // tree results in a palindrome
    static boolean isPalindrome(Node root) {
        if (root == null) return true;

        Queue<Node> q = new LinkedList<>();
        Stack<Character> st = new Stack<>();
        q.add(root);

        // Traverse the tree and push the node
        // values into stack.
        while (!q.isEmpty()) {
            Node curr = q.poll();

            // Push the curr value into stack.
            st.push(curr.data);

            // Push left node
            if (curr.left != null)
                q.add(curr.left);

            // Push right node
            if (curr.right != null)
                q.add(curr.right);
        }

        // Again traverse the tree and compare
        // node values with stack top.
        q.add(root);
        while (!q.isEmpty()) {
            Node curr = q.poll();

            // If values don't match, then
            // it is not palindrome.
            if (curr.data != st.peek())
                return false;
            else st.pop();

            if (curr.left != null)
                q.add(curr.left);

            if (curr.right != null)
                q.add(curr.right);
        }

        return true;
    }

    public static void main(String[] args) {

        // Binary tree
        //       R
        //      / \
        //     A   D
        //   / \
        //   A   R
        Node root = new Node('R');
        root.left = new Node('A');
        root.right = new Node('D');
        root.left.left = new Node('A');
        root.left.right = new Node('R');

        if (isPalindrome(root))
            System.out.println("True");
        else
            System.out.println("False");
    }
}
Python
# Python program to check if level order
# traversal of binary tree is palindrome.
from collections import deque

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function that returns true if the
# level order traversal of the
# tree results in a palindrome
def isPalindrome(root):
    if root is None:
        return True

    q = deque()
    st = []
    q.append(root)

    # Traverse the tree and push the node
    # values into stack.
    while len(q) > 0:
        curr = q.popleft()

        # Push the curr value into stack.
        st.append(curr.data)

        # Push left node
        if curr.left is not None:
            q.append(curr.left)

        # Push right node
        if curr.right is not None:
            q.append(curr.right)

    # Again traverse the tree and compare
    # node values with stack top.
    q.append(root)
    while len(q) > 0:
        curr = q.popleft()

        # If values don't match, then
        # it is not palindrome.
        if curr.data != st[-1]:
            return False
        else:
            st.pop()

        if curr.left is not None:
            q.append(curr.left)

        if curr.right is not None:
            q.append(curr.right)

    return True

if __name__ == "__main__":

    # Binary tree
    #       R
    #      / \
    #     A   D
    #   / \
    #   A   R
    root = Node('R')
    root.left = Node('A')
    root.right = Node('D')
    root.left.left = Node('A')
    root.left.right = Node('R')

    if isPalindrome(root):
        print("True")
    else:
        print("False")
C#
// C# program to check if level order
// traversal of binary tree is palindrome.
using System;
using System.Collections.Generic;

class Node {
    public char data;
    public Node left, right;

    public Node(char x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
    
    // Function that returns true if the
    // level order traversal of the
    // tree results in a palindrome
    static bool isPalindrome(Node root) {
        if (root == null) return true;

        Queue<Node> q = new Queue<Node>();
        Stack<char> st = new Stack<char>();
        q.Enqueue(root);

        // Traverse the tree and push the node
        // values into stack.
        while (q.Count > 0) {
            Node curr = q.Dequeue();

            // Push the curr value into stack.
            st.Push(curr.data);

            // Push left node
            if (curr.left != null)
                q.Enqueue(curr.left);

            // Push right node
            if (curr.right != null)
                q.Enqueue(curr.right);
        }

        // Again traverse the tree and compare
        // node values with stack top.
        q.Enqueue(root);
        while (q.Count > 0) {
            Node curr = q.Dequeue();

            // If values don't match, then
            // it is not palindrome.
            if (curr.data != st.Peek())
                return false;
            else st.Pop();

            if (curr.left != null)
                q.Enqueue(curr.left);

            if (curr.right != null)
                q.Enqueue(curr.right);
        }

        return true;
    }

    static void Main(string[] args) {

        // Binary tree
        //       R
        //      / \
        //     A   D
        //   / \
        //   A   R
        Node root = new Node('R');
        root.left = new Node('A');
        root.right = new Node('D');
        root.left.left = new Node('A');
        root.left.right = new Node('R');

        if (isPalindrome(root))
            Console.WriteLine("True");
        else
            Console.WriteLine("False");
    }
}
JavaScript
// JavaScript program to check if level order
// traversal of binary tree is palindrome.

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function that returns true if the
// level order traversal of the
// tree results in a palindrome
function isPalindrome(root) {
    if (root === null) return true;

    let q = [];
    let st = [];
    q.push(root);

    // Traverse the tree and push the node
    // values into stack.
    while (q.length > 0) {
        let curr = q.shift();

        // Push the curr value into stack.
        st.push(curr.data);

        // Push left node
        if (curr.left !== null)
            q.push(curr.left);

        // Push right node
        if (curr.right !== null)
            q.push(curr.right);
    }

    // Again traverse the tree and compare
    // node values with stack top.
    q.push(root);
    while (q.length > 0) {
        let curr = q.shift();

        // If values don't match, then
        // it is not palindrome.
        if (curr.data !== st[st.length - 1])
            return false;
        else st.pop();

        if (curr.left !== null)
            q.push(curr.left);

        if (curr.right !== null)
            q.push(curr.right);
    }

    return true;
}

// Binary tree
//       R
//      / \
//     A   D
//   / \
//   A   R
let root = new Node('R');
root.left = new Node('A');
root.right = new Node('D');
root.left.left = new Node('A');
root.left.right = new Node('R');

if (isPalindrome(root))
    console.log("True");
else
    console.log("False");

Output
True

Time Complexity: O(n), where n is the number of nodes in binary tree.
Auxiliary Space: O(n). 



Next Article
Practice Tags :

Similar Reads