Lexicographically smallest Palindromic Path in a Binary Tree
Last Updated :
07 Mar, 2022
Given a Binary Tree with each node representing an alphabet, the task is to find lexicographically smallest palindromic root to leaf path. If no palindromic path exists, print “No Palindromic Path exists”.
Examples:
Input:
a
/ \
c b
/ \ / \
a g b x
\
a
Output:
abba
Explanation:
There were total 4 root to leaf paths out of which 2 paths(i.e., "aca" and "abba") were palindromic paths but as "abba" is lexicographically smaller, print "abba" as output.
Input:
a
/ \
z k
/ \ / \
s e k u
\
e
Output:
No Palindromic Path exists
Approach: Follow the steps to solve the problem
- The main idea is to use Preorder Traversal
- Traverse the tree in Preorder fashion.
- Keep storing the node values in a string.
- As soon as a leaf node is reached, check if the string formed from a root to leaf path is a palindrome or not.
- If it's a palindrome store it in a variable only if it's lexicographically the smallest palindromic path.
- Print the palindrome, if it exists.
Below is the implementation of the above approach:
C++
// C++ program
// for the above approach
#include <bits/stdc++.h>
using namespace std;
// Struct binary tree node
struct Node {
char data;
Node *left, *right;
};
// Function to create a new node
Node* newNode(char data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Function to check if the
// string is palindrome or not
bool checkPalindrome(string s)
{
int low = 0, high = (int)s.size() - 1;
while (low < high) {
if (s[low] != s[high])
return false;
low++;
high--;
}
return true;
}
// Function to find the lexicographically
// smallest palindromic path in the Binary Tree
void lexicographicallySmall(Node* root, string s,
string& finalAns)
{
// Base case
if (root == NULL)
return;
// Append current node's
// data to the string
s += root->data;
// Check if a node is leaf or not
if (!root->left and !root->right) {
if (checkPalindrome(s)) {
// Check for the 1st
// Palindromic Path
if (finalAns == "$")
finalAns = s;
// Store lexicographically the
// smallest palindromic path
else
finalAns = min(finalAns, s);
}
return;
}
// Recursively traverse left subtree
lexicographicallySmall(root->left,
s, finalAns);
// Recursively traverse right subtree
lexicographicallySmall(root->right,
s, finalAns);
}
// Function to get smallest
// lexicographical palindromic
// path
void getPalindromePath(Node* root)
{
// Variable which stores
// the final result
string finalAns = "$";
// Function call to compute
// lexicographically smallest
// palindromic Path
lexicographicallySmall(root, "",
finalAns);
if (finalAns == "$")
cout << "No Palindromic Path exists";
else
cout << finalAns;
}
// Driver Code
int main()
{
// Construct binary tree
Node* root = newNode('a');
root->left = newNode('c');
root->left->left = newNode('a');
root->left->right = newNode('g');
root->right = newNode('b');
root->right->left = newNode('b');
root->right->right = newNode('x');
root->right->left->right = newNode('a');
getPalindromePath(root);
return 0;
}
Java
// Java program
// for the above approach
import java.util.*;
class GFG
{
static String finalAns="";
// Struct binary tree node
static class Node
{
char data;
Node left, right;
};
// Function to create a new node
static Node newNode(char data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Function to check if the
// String is palindrome or not
static boolean checkPalindrome(String s)
{
int low = 0, high = (int)s.length() - 1;
while (low < high)
{
if (s.charAt(low) != s.charAt(high))
return false;
low++;
high--;
}
return true;
}
// Function to find the lexicographically
// smallest palindromic path in the Binary Tree
static void lexicographicallySmall(Node root, String s)
{
// Base case
if (root == null)
return;
// Append current node's
// data to the String
s += root.data;
// Check if a node is leaf or not
if (root.left == null && root.right == null)
{
if (checkPalindrome(s))
{
// Check for the 1st
// Palindromic Path
if (finalAns == "$")
finalAns = s;
// Store lexicographically the
// smallest palindromic path
else
finalAns = finalAns.compareTo(s) <= 0 ? finalAns:s;
}
return;
}
// Recursively traverse left subtree
lexicographicallySmall(root.left,
s);
// Recursively traverse right subtree
lexicographicallySmall(root.right,
s);
}
// Function to get smallest
// lexicographical palindromic
// path
static void getPalindromePath(Node root)
{
// Variable which stores
// the final result
finalAns = "$";
// Function call to compute
// lexicographically smallest
// palindromic Path
lexicographicallySmall(root, "");
if (finalAns == "$")
System.out.print("No Palindromic Path exists");
else
System.out.print(finalAns);
}
// Driver Code
public static void main(String[] args)
{
// Construct binary tree
Node root = newNode('a');
root.left = newNode('c');
root.left.left = newNode('a');
root.left.right = newNode('g');
root.right = newNode('b');
root.right.left = newNode('b');
root.right.right = newNode('x');
root.right.left.right = newNode('a');
getPalindromePath(root);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program
# for the above approach
# Struct binary tree node
class Node:
def __init__(self, d):
self.data = d
self.left = None
self.right = None
# Function to check if the
# is palindrome or not
def checkPalindrome(s):
low, high = 0, len(s) - 1
while (low < high):
if (s[low] != s[high]):
return False
low += 1
high -= 1
return True
# Function to find the lexicographically
# smallest palindromic path in the Binary Tree
def lexicographicallySmall(root, s):
global finalAns
# Base case
if (root == None):
return
# Append current node's
# data to the string
s += root.data
# Check if a node is leaf or not
if (not root.left and not root.right):
if (checkPalindrome(s)):
# Check for the 1st
# Palindromic Path
if (finalAns == "$"):
finalAns = s
# Store lexicographically the
# smallest palindromic path
else:
finalAns = min(finalAns, s)
return
# Recursively traverse left subtree
lexicographicallySmall(root.left, s)
# Recursively traverse right subtree
lexicographicallySmall(root.right, s)
# Function to get smallest
# lexicographical palindromic
# path
def getPalindromePath(root):
global finalAns
# Variable which stores
# the final result
finalAns = "$"
# Function call to compute
# lexicographically smallest
# palindromic Path
lexicographicallySmall(root, "")
if (finalAns == "$"):
print("No Palindromic Path exists")
else:
print(finalAns)
# Driver Code
if __name__ == '__main__':
finalAns = ""
# Construct binary tree
root = Node('a')
root.left = Node('c')
root.left.left = Node('a')
root.left.right = Node('g')
root.right = Node('b')
root.right.left = Node('b')
root.right.right = Node('x')
root.right.left.right = Node('a')
getPalindromePath(root)
# This code is contributed by mohit kumar 29.
C#
// C# program
// for the above approach
using System;
public class GFG
{
static String finalAns = "";
// Struct binary tree node
class Node
{
public char data;
public Node left, right;
};
// Function to create a new node
static Node newNode(char data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Function to check if the
// String is palindrome or not
static bool checkPalindrome(String s)
{
int low = 0, high = (int)s.Length - 1;
while (low < high)
{
if (s[low] != s[high])
return false;
low++;
high--;
}
return true;
}
// Function to find the lexicographically
// smallest palindromic path in the Binary Tree
static void lexicographicallySmall(Node root, String s)
{
// Base case
if (root == null)
return;
// Append current node's
// data to the String
s += root.data;
// Check if a node is leaf or not
if (root.left == null && root.right == null)
{
if (checkPalindrome(s))
{
// Check for the 1st
// Palindromic Path
if (finalAns == "$")
finalAns = s;
// Store lexicographically the
// smallest palindromic path
else
finalAns = finalAns.CompareTo(s) <= 0 ? finalAns:s;
}
return;
}
// Recursively traverse left subtree
lexicographicallySmall(root.left,
s);
// Recursively traverse right subtree
lexicographicallySmall(root.right,
s);
}
// Function to get smallest
// lexicographical palindromic
// path
static void getPalindromePath(Node root)
{
// Variable which stores
// the readonly result
finalAns = "$";
// Function call to compute
// lexicographically smallest
// palindromic Path
lexicographicallySmall(root, "");
if (finalAns == "$")
Console.Write("No Palindromic Path exists");
else
Console.Write(finalAns);
}
// Driver Code
public static void Main(String[] args)
{
// Construct binary tree
Node root = newNode('a');
root.left = newNode('c');
root.left.left = newNode('a');
root.left.right = newNode('g');
root.right = newNode('b');
root.right.left = newNode('b');
root.right.right = newNode('x');
root.right.left.right = newNode('a');
getPalindromePath(root);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program for the above approach
let finalAns="";
// Struct binary tree node
class Node
{
constructor(data) {
this.left = null;
this.right = null;
this.data = data;
}
}
// Function to create a new node
function newNode(data)
{
let temp = new Node(data);
return temp;
}
// Function to check if the
// String is palindrome or not
function checkPalindrome(s)
{
let low = 0, high = s.length - 1;
while (low < high)
{
if (s[low] != s[high])
return false;
low++;
high--;
}
return true;
}
// Function to find the lexicographically
// smallest palindromic path in the Binary Tree
function lexicographicallySmall(root, s)
{
// Base case
if (root == null)
return;
// Append current node's
// data to the String
s += root.data;
// Check if a node is leaf or not
if (root.left == null && root.right == null)
{
if (checkPalindrome(s))
{
// Check for the 1st
// Palindromic Path
if (finalAns == "$")
finalAns = s;
// Store lexicographically the
// smallest palindromic path
else
finalAns = finalAns.localeCompare(s) <= 0 ? finalAns:s;
}
return;
}
// Recursively traverse left subtree
lexicographicallySmall(root.left, s);
// Recursively traverse right subtree
lexicographicallySmall(root.right, s);
}
// Function to get smallest
// lexicographical palindromic
// path
function getPalindromePath(root)
{
// Variable which stores
// the final result
finalAns = "$";
// Function call to compute
// lexicographically smallest
// palindromic Path
lexicographicallySmall(root, "");
if (finalAns == "$")
document.write("No Palindromic Path exists");
else
document.write(finalAns);
}
// Construct binary tree
let root = newNode('a');
root.left = newNode('c');
root.left.left = newNode('a');
root.left.right = newNode('g');
root.right = newNode('b');
root.right.left = newNode('b');
root.right.right = newNode('x');
root.right.left.right = newNode('a');
getPalindromePath(root);
// This code is contributed by suresh07.
</script>
Time Complexity: O(N2)
Auxiliary Space: O(N2)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read