Open In App

Check if Inorder traversal of a Binary Tree is palindrome or not

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

Given a binary tree, the task is to check if its Inorder Sequence is a palindrome or not. 

Examples: 

Input:

check-if-inorder-traversal-of-a-binary-tree-is-palindrome-or-not

Output: True 
Explanation: The Inorder sequence of the tree is “bbaaabb” which is a palindromic string.

Input:

check-if-inorder-traversal-of-a-binary-tree-is-palindrome-or-not-2

Output: False 
Explanation: The Inorder sequence of the tree is “bbdaabb” which is not a palindromic string. 

[Naive Approach] Using In-Order Traversal – O(n) Time and O(n) Space

The idea is to traverse the binary tree using in-order traversal and push the node values into an array. Then check if the array is a palindrome using two pointers approach.

Below is the implementation of the above approach:

C++
// C++ program to check if inorder
// 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;
    }
};

// Recursive function to store
// in-order traversal in array.
void storeNodes(Node* root, vector<char>&arr) {
    if (root==nullptr) return;
    
    storeNodes(root->left, arr);
    arr.push_back(root->data);
    storeNodes(root->right, arr);
}

// Function that returns true if the
// inorder traversal of the
// tree results in a palindrome
bool isPalindrome(Node* root) {
    if (root == nullptr) return true;
    
    // store in-order of tree in 
    // array.
    vector<char> arr;
    storeNodes(root, arr);
    
    // Check if the given array 
    // is a palindrome.
    int i = 0, j = arr.size()-1;
    while (i<j) {
        
        // if char mismatch, return
        // false.
        if (arr[i]!=arr[j]) 
            return false;
            
        i++;
        j--;
    }
    
    return true;
}

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

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

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

class Node {
    char data;
    Node left, right;

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

class GfG {

    // Recursive function to store
    // in-order traversal in array.
    static void storeNodes(Node root, 
                           ArrayList<Character> arr) {
        if (root == null) return;
        
        storeNodes(root.left, arr);
        arr.add(root.data);
        storeNodes(root.right, arr);
    }

    // Function that returns true if the
    // inorder traversal of the
    // tree results in a palindrome
    static boolean isPalindrome(Node root) {
        if (root == null) return true;
        
        // store in-order of tree in 
        // array.
        ArrayList<Character> arr = new ArrayList<>();
        storeNodes(root, arr);
        
        // Check if the given array 
        // is a palindrome.
        int i = 0, j = arr.size() - 1;
        while (i < j) {
            
            // if char mismatch, return
            // false.
            if (arr.get(i) != arr.get(j)) 
                return false;
                
            i++;
            j--;
        }
        
        return true;
    }

    public static void main(String[] args) {
        
        // Binary tree
        //        a
        //       / \  
        //      b   b  
        //     / \  / \  
        //    b   a a  b
        Node root = new Node('a');
        root.left = new Node('b');
        root.right = new Node('b');
        root.left.left = new Node('b');
        root.left.right = new Node('a');
        root.right.left = new Node('a');
        root.right.right = new Node('b');

        if (isPalindrome(root))
            System.out.println("True");
        else
            System.out.println("False");
    }
}
Python
# Python program to check if inorder
# traversal of binary tree is palindrome.

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

# Recursive function to store
# in-order traversal in array.
def storeNodes(root, arr):
    if root is None:
        return
    storeNodes(root.left, arr)
    arr.append(root.data)
    storeNodes(root.right, arr)

# Function that returns true if the
# inorder traversal of the
# tree results in a palindrome
def isPalindrome(root):
    if root is None:
        return True
    
    # store in-order of tree in 
    # array.
    arr = []
    storeNodes(root, arr)
    
    # Check if the given array 
    # is a palindrome.
    i, j = 0, len(arr) - 1
    while i < j:
        
        # if char mismatch, return
        # false.
        if arr[i] != arr[j]:
            return False
            
        i += 1
        j -= 1
    
    return True

if __name__ == "__main__":
    
    # Binary tree
    #        a
    #       / \  
    #      b   b  
    #     / \  / \  
    #    b   a a  b
    root = Node('a')
    root.left = Node('b')
    root.right = Node('b')
    root.left.left = Node('b')
    root.left.right = Node('a')
    root.right.left = Node('a')
    root.right.right = Node('b')

    if isPalindrome(root):
        print("True")
    else:
        print("False")
C#
// C# program to check if inorder
// 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 {

    // Recursive function to store
    // in-order traversal in array.
    static void storeNodes(Node root, List<char> arr) {
        if (root == null) return;
        
        storeNodes(root.left, arr);
        arr.Add(root.data);
        storeNodes(root.right, arr);
    }

    // Function that returns true if the
    // inorder traversal of the
    // tree results in a palindrome
    static bool isPalindrome(Node root) {
        if (root == null) return true;
        
        // store in-order of tree in 
        // array.
        List<char> arr = new List<char>();
        storeNodes(root, arr);
        
        // Check if the given array 
        // is a palindrome.
        int i = 0, j = arr.Count - 1;
        while (i < j) {
            
            // if char mismatch, return
            // false.
            if (arr[i] != arr[j]) 
                return false;
                
            i++;
            j--;
        }
        
        return true;
    }

    static void Main(string[] args) {
        
        // Binary tree
        //        a
        //       / \  
        //      b   b  
        //     / \  / \  
        //    b   a a  b
        Node root = new Node('a');
        root.left = new Node('b');
        root.right = new Node('b');
        root.left.left = new Node('b');
        root.left.right = new Node('a');
        root.right.left = new Node('a');
        root.right.right = new Node('b');

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

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

// Recursive function to store
// in-order traversal in array.
function storeNodes(root, arr) {
    if (root === null) return;
    storeNodes(root.left, arr);
    arr.push(root.data);
    storeNodes(root.right, arr);
}

// Function that returns true if the
// inorder traversal of the
// tree results in a palindrome
function isPalindrome(root) {
    if (root === null) return true;
    
    // store in-order of tree in 
    // array.
    let arr = [];
    storeNodes(root, arr);
    
    // Check if the given array 
    // is a palindrome.
    let i = 0, j = arr.length - 1;
    while (i < j) {
        
        // if char mismatch, return
        // false.
        if (arr[i] !== arr[j]) 
            return false;
            
        i++;
        j--;
    }
    
    return true;
}

// Binary tree
//        a
//       / \  
//      b   b  
//     / \  / \  
//    b   a a  b
let root = new Node('a');
root.left = new Node('b');
root.right = new Node('b');
root.left.left = new Node('b');
root.left.right = new Node('a');
root.right.left = new Node('a');
root.right.right = new Node('b');

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

Output
True

[Expected Approach] Converting Tree To Doubly Linked List – O(n) Time and O(1) Space

The idea is to use morris traversal to convert the Binary tree into doubly linked list. Then check if the resultant doubly linked list is a palindrome.

Below is the implementation of above approach: 

C++
// C++ program to check if inorder
// 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 to perform Morris Traversal and convert
// binary tree to doubly linked list (DLL)
// It returns the head and tail node of list.
pair<Node*,Node*> treeToList(Node* root) {
    
    // head and tail node for the dll
    Node* head = nullptr, *tail = nullptr;
    
    Node* curr = root;
    
    while (curr != nullptr) {
        
        // if left tree does not exists,
        // then add the curr node to the 
        // dll and set curr = curr->right
        if (curr->left == nullptr) {
            if (head == nullptr) {
                head = tail = curr;
            }
            else {
                tail->right = curr;
                curr->left = tail;
                tail = curr;
            }
            curr = curr->right;    
        }
        else {
            Node* pred = curr->left;
            
            // find the inorder predecessor 
            while (pred->right != nullptr && 
            pred->right != curr) {
                pred = pred->right;
            }
            
            // create a linkage between pred and
            // curr 
            if (pred->right == nullptr) {
                pred->right = curr;
                curr = curr->left;
            }
            
            // if pred->right = curr, it means 
            // we have processed the left subtree,
            // and we can add curr node to list
            else {
                tail->right = curr;
                curr->left = tail;
                tail = curr;
                
                curr = curr->right;
            }
        }
    }
    
    return {head, tail};
}

// Function that returns true if the
// inorder traversal of the
// tree results in a palindrome
bool isPalindrome(Node* root) {
    if (root == nullptr) return true;
    
    // Convert the tree into 
    // doubly linked list.
    pair<Node*,Node*> res = treeToList(root);
    
    Node *left = res.first, *right = res.second;
    
    // Check if the doubly linked list is 
    // a palindrome.
    while (left!=right && left->left!=right) {
        
        // If char mismatch, return
        // false.
        if (left->data != right->data)
            return false;
            
        // Move the pointers
        left = left->right;
        right = right->left;
    }
    
    return true;
}

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

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

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

class Node {
    char data;
    Node left, right;

    Node(char x) {
        data = x;
        left = null;
        right = null;
    }
}
class Pair {
    Node first, second;

    Pair(Node first, Node second) {
        this.first = first;
        this.second = second;
    }
}

class GfG {

    // Function to perform Morris Traversal and convert
    // binary tree to doubly linked list (DLL)
    // It returns the head and tail node of list.
    static Pair treeToList(Node root) {
        Node head = null, tail = null;
        Node curr = root;

        while (curr != null) {
            if (curr.left == null) {
                if (head == null) {
                    head = tail = curr;
                } else {
                    tail.right = curr;
                    curr.left = tail;
                    tail = curr;
                }
                curr = curr.right;
            } else {
                Node pred = curr.left;

                // find the inorder predecessor 
                while (pred.right != null &&
                pred.right != curr) {
                    pred = pred.right;
                }

                // create a linkage between 
              	// pred and curr 
                if (pred.right == null) {
                    pred.right = curr;
                    curr = curr.left;
                } else {
                    tail.right = curr;
                    curr.left = tail;
                    tail = curr;
                    curr = curr.right;
                }
            }
        }
        
        return new Pair(head, tail);
    }

    // Function that returns true if the
    // inorder traversal of the
    // tree results in a palindrome
    static boolean isPalindrome(Node root) {
        if (root == null) return true;
        
        Pair res = treeToList(root);
        Node left = res.first, right = res.second;

        // Check if the doubly linked list
      	// is a palindrome.
        while (left != right && left.left != right) {
            if (left.data != right.data)
                return false;
            
            left = left.right;
            right = right.left;
        }

        return true;
    }

    public static void main(String[] args) {
        
        // Binary tree
        //        a
        //       / \  
        //      b   b  
        //     / \  / \  
        //    b   a a  b
        Node root = new Node('a');
        root.left = new Node('b');
        root.right = new Node('b');
        root.left.left = new Node('b');
        root.left.right = new Node('a');
        root.right.left = new Node('a');
        root.right.right = new Node('b');

        if (isPalindrome(root))
            System.out.println("True");
        else
            System.out.println("False");
    }
}
Python
# Python program to check if inorder
# traversal of binary tree is palindrome.

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

# Function to perform Morris Traversal and convert
# binary tree to doubly linked list (DLL)
# It returns the head and tail node of list.
def treeToList(root):
    head = tail = None
    curr = root

    while curr is not None:
        if curr.left is None:
            if head is None:
                head = tail = curr
            else:
                tail.right = curr
                curr.left = tail
                tail = curr
            curr = curr.right
        else:
            pred = curr.left

            # find the inorder predecessor 
            while pred.right is not None and pred.right != curr:
                pred = pred.right

            # create a linkage between pred and curr 
            if pred.right is None:
                pred.right = curr
                curr = curr.left
            else:
                tail.right = curr
                curr.left = tail
                tail = curr
                curr = curr.right

    return head, tail

# Function that returns true if the
# inorder traversal of the
# tree results in a palindrome
def isPalindrome(root):
    if root is None:
        return True
    
    head, tail = treeToList(root)
    
    # Check if the doubly linked list is
    # a palindrome.
    left, right = head, tail
    while left != right and left.left != right:
        if left.data != right.data:
            return False
        left = left.right
        right = right.left

    return True

if __name__ == "__main__":
    
    # Binary tree
    #        a
    #       / \  
    #      b   b  
    #     / \  / \  
    #    b   a a  b
    root = Node('a')
    root.left = Node('b')
    root.right = Node('b')
    root.left.left = Node('b')
    root.left.right = Node('a')
    root.right.left = Node('a')
    root.right.right = Node('b')

    if isPalindrome(root):
        print("True")
    else:
        print("False")
C#
// C# program to check if inorder
// 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 Pair {
    public Node first, second;

    public Pair(Node first, Node second) {
        this.first = first;
        this.second = second;
    }
}

class GfG {

    // Function to perform Morris Traversal and convert
    // binary tree to doubly linked list (DLL)
    // It returns the head and tail node of list.
    static Pair treeToList(Node root) {
        Node head = null, tail = null;
        Node curr = root;

        while (curr != null) {
            if (curr.left == null) {
                if (head == null) {
                    head = tail = curr;
                } else {
                    tail.right = curr;
                    curr.left = tail;
                    tail = curr;
                }
                curr = curr.right;
            } else {
                Node pred = curr.left;

                // find the inorder predecessor 
                while (pred.right != null && pred.right != curr) {
                    pred = pred.right;
                }

                // create a linkage between 
              	// pred and curr 
                if (pred.right == null) {
                    pred.right = curr;
                    curr = curr.left;
                } else {
                    tail.right = curr;
                    curr.left = tail;
                    tail = curr;
                    curr = curr.right;
                }
            }
        }
        
        return new Pair(head, tail);
    }

    // Function that returns true if the
    // inorder traversal of the
    // tree results in a palindrome
    static bool isPalindrome(Node root) {
        if (root == null) return true;
        
        Pair res = treeToList(root);
        Node left = res.first, right = res.second;

        // Check if the doubly linked list 
      	// is a palindrome.
        while (left != right && left.left != right) {
            if (left.data != right.data)
                return false;
            
            left = left.right;
            right = right.left;
        }

        return true;
    }

    static void Main(string[] args) {
        
        // Binary tree
        //        a
        //       / \  
        //      b   b  
        //     / \  / \  
        //    b   a a  b
        Node root = new Node('a');
        root.left = new Node('b');
        root.right = new Node('b');
        root.left.left = new Node('b');
        root.left.right = new Node('a');
        root.right.left = new Node('a');
        root.right.right = new Node('b');

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

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

// Function to perform Morris Traversal and convert
// binary tree to doubly linked list (DLL)
// It returns the head and tail node of list.
function treeToList(root) {
    let head = null, tail = null;
    let curr = root;

    while (curr !== null) {
        if (curr.left === null) {
            if (head === null) {
                head = tail = curr;
            } else {
                tail.right = curr;
                curr.left = tail;
                tail = curr;
            }
            curr = curr.right;
        } else {
            let pred = curr.left;

            // find the inorder predecessor 
            while (pred.right !== null && 
            				pred.right !== curr) {
                pred = pred.right;
            }

            // create a linkage between
            // pred and curr 
            if (pred.right === null) {
                pred.right = curr;
                curr = curr.left;
            } else {
                tail.right = curr;
                curr.left = tail;
                tail = curr;
                curr = curr.right;
            }
        }
    }
    
    return { head, tail };
}

// Function that returns true if the
// inorder traversal of the
// tree results in a palindrome
function isPalindrome(root) {
    if (root === null) return true;
    
    let res = treeToList(root);
    let left = res.head, right = res.tail;

    // Check if the doubly linked list
    // is a palindrome.
    while (left !== right && left.left !== right) {
        if (left.data !== right.data)
            return false;
        
        left = left.right;
        right = right.left;
    }

    return true;
}

// Binary tree
//        a
//       / \  
//      b   b  
//     / \  / \  
//    b   a a  b
let root = new Node('a');
root.left = new Node('b');
root.right = new Node('b');
root.left.left = new Node('b');
root.left.right = new Node('a');
root.right.left = new Node('a');
root.right.right = new Node('b');

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

Output
True


Next Article

Similar Reads