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”.
/ \ / \
a g b x
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.
/ \ / \
s e k u
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:
Time Complexity: O(N2)
Auxiliary Space: O(N2)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.